javaSwing打开窗口,随机生成一个1-100以内的数字作为谜底。在输入框输入另一个数字,点击按钮,如果输入框里的数字比谜底大,则谈提示框显示“太大了”,如果比谜底小则显示“太小了”,一样则显示“猜对了”。
时间: 2024-03-27 10:39:53 浏览: 69
好的,这是一个猜数字的小游戏。实现这个游戏需要以下步骤:
1. 创建一个 JFrame 窗口,并在窗口中添加一个 JLabel 用于显示游戏信息,一个 JTextField 用于输入数字,一个 JButton 用于提交答案。
2. 使用 Random 类生成一个 1-100 之间的随机数作为谜底。
3. 在 JButton 的 ActionListener 中获取用户输入的数字,并与谜底进行比较。
4. 如果用户输入的数字比谜底大,则使用 JOptionPane.showConfirmDialog() 方法弹出提示框,提示用户“太大了”;如果比谜底小,则提示“太小了”;如果猜中了,则提示“猜对了”。
下面是实现这个游戏的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class GuessNumberGame extends JFrame implements ActionListener {
private JLabel label = new JLabel("请输入1-100之间的数字:");
private JTextField textField = new JTextField(20);
private JButton button = new JButton("猜");
private int answer;
public GuessNumberGame() {
super("猜数字游戏");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(label);
add(textField);
add(button);
// 生成随机数作为谜底
Random random = new Random();
answer = random.nextInt(100) + 1;
button.addActionListener(this);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// 获取用户输入的数字
String input = textField.getText();
int guess = Integer.parseInt(input);
if (guess > answer) {
JOptionPane.showConfirmDialog(null, "太大了", "提示", JOptionPane.DEFAULT_OPTION);
} else if (guess < answer) {
JOptionPane.showConfirmDialog(null, "太小了", "提示", JOptionPane.DEFAULT_OPTION);
} else {
JOptionPane.showConfirmDialog(null, "猜对了", "提示", JOptionPane.DEFAULT_OPTION);
dispose();
}
// 清空输入框
textField.setText("");
}
public static void main(String[] args) {
new GuessNumberGame();
}
}
```
运行程序,就可以开始玩猜数字游戏啦!
阅读全文
相关推荐













