设计一个鼠标点击速度比赛游戏。 (1)显示一个按钮和文本框。 (2)文本框显示鼠标点击次数

本文介绍了一个简单的Java Swing应用程序,用于创建一个鼠标点击速度比赛游戏。该程序包含一个按钮和一个文本框,通过连续点击按钮来记录点击次数,并在文本框中实时显示点击总数。

/*设计一个鼠标点击速度比赛游戏。
 *(1)显示一个按钮和文本框。
 *(2)文本框显示鼠标点击次数
 **/
import javax.swing.*;//引用
import java.awt.*;
import java.awt.event.*;




public class SBBS extends JFrame implements ActionListener {
JTextField ab;//定义全局变量
int a;
SBBS (){
JFrame jf = new JFrame("鼠标点击速度大比拼");
jf.setVisible(true);
jf.setSize(400, 600);//设置窗口初显大小
jf.setLocationRelativeTo(null);
JLabel La=new JLabel("点击次数");//标签
ab= new JTextField(25);// 文本框
JButton b1= new JButton("请连续点击");//按钮
b1.addActionListener(this);
jf.add(La);//将组件添加到面板
jf.add(ab);
jf.add(b1);
jf.setLayout(new FlowLayout());
}
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand() ;
if(s.equals("请连续点击"))
ab.setText(""+a++);
}




public static void main(String[] args) {
new SBBS() ;
}
}
以下是实现按钮1鼠标划过事件触发后随机移动且不被文本框按钮2挡住的 C# WinForm 程序代码示例: ```csharp using System; using System.Drawing; using System.Windows.Forms; namespace ButtonRandomMoveOnMouseHover { public partial class Form1 : Form { private Random random = new Random(); public Form1() { InitializeComponent(); button1.MouseEnter += button1_MouseEnter; } private void button1_MouseEnter(object sender, EventArgs e) { MoveButtonRandomly(button1); } private void MoveButtonRandomly(Button button) { int maxX = this.ClientSize.Width - button.Width; int maxY = this.ClientSize.Height - button.Height; int newX, newY; do { newX = random.Next(0, maxX); newY = random.Next(0, maxY); } while (IsOverlapping(button, new Point(newX, newY))); button.Location = new Point(newX, newY); } private bool IsOverlapping(Button button, Point newLocation) { Rectangle newRect = new Rectangle(newLocation, button.Size); foreach (Control control in this.Controls) { if (control != button && (control is Button || control is TextBox)) { if (newRect.IntersectsWith(control.Bounds)) { return true; } } } return false; } } } ``` ### 代码解释 1. **`Random` 对象**:用于生成随机数,以确定按钮的新位置。 2. **`button1_MouseEnter` 方法**:当鼠标划过按钮1时,调用 `MoveButtonRandomly` 方法来随机移动按钮。 3. **`MoveButtonRandomly` 方法**:计算按钮可移动的最大 `X` `Y` 坐标,然后生成随机的新位置,直到新位置不会与文本框按钮2重叠。 4. **`IsOverlapping` 方法**:检查按钮的新位置是否与文本框按钮2重叠。 ### 相关设置 1. 创建一个新的 WinForm 项目。 2. 在设计器中添加一个按钮(`button1`)、一个文本框(`textBox1`)一个按钮(`button2`)。 3. 确保 `button1` 的 `MouseEnter` 事件绑定到 `button1_MouseEnter` 方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值