java用gui界面实现300到800的猜数游戏
时间: 2024-03-26 07:38:22 浏览: 69
好的,这个游戏可以使用Java的Swing库来实现GUI界面,以下是一个简单的实现方式:
1. 创建一个JFrame窗口,设置标题和大小。
2. 创建一个JLabel用于显示游戏提示信息。
3. 创建一个JTextField用于输入猜测的数字。
4. 创建一个JButton用于提交猜测。
5. 在JButton的ActionListener中,获取输入的数字并与正确答案进行比较,根据比较结果更新提示信息。
6. 当猜测正确时,弹出提示窗口显示胜利信息并退出游戏。
以下是一个示例代码:
```java
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GuessNumberGame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private int answer = (int) (Math.random() * 501) + 300; // 生成随机数
private JLabel promptLabel;
private JTextField guessTextField;
public GuessNumberGame() {
setTitle("猜数字游戏");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
promptLabel = new JLabel("请输入一个300到800之间的整数:");
add(promptLabel);
guessTextField = new JTextField(10);
add(guessTextField);
JButton submitButton = new JButton("提交");
add(submitButton);
submitButton.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int guess;
try {
guess = Integer.parseInt(guessTextField.getText());
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入一个有效的整数!");
return;
}
if (guess < 300 || guess > 800) {
JOptionPane.showMessageDialog(this, "请输入一个300到800之间的整数!");
return;
}
if (guess == answer) {
JOptionPane.showMessageDialog(this, "恭喜你猜对了!");
System.exit(0);
} else if (guess < answer) {
promptLabel.setText("你猜的数字太小了,请再试一次:");
} else {
promptLabel.setText("你猜的数字太大了,请再试一次:");
}
}
public static void main(String[] args) {
new GuessNumberGame();
}
}
```
运行程序后,会显示一个输入框和一个提交按钮,输入一个300到800之间的数字并点击提交按钮进行猜测,程序会根据猜测结果更新提示信息,直到猜测正确为止。
阅读全文
相关推荐














