猜数字游戏java,要用到GUI图形界面,且运行要有次数限制
1个回答
展开全部
测试效果如图
参考java代码和注释如下
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class GuessNumFrame extends JFrame {
private JPanel contentPane;
private int num;
private final JTextField jtfInput;
private final JLabel label;
static final int MAX_TIMES = 5; // 最多可以尝试5次
private int times = 0;// 记录尝试次数
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GuessNumFrame frame = new GuessNumFrame();
frame.setVisible(true);// 窗口可见
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GuessNumFrame() {
setTitle("猜数字");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(360, 160);// 窗口大小
setLocationRelativeTo(null);// 居中
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.CENTER);
panel_1.setLayout(new GridLayout(3, 1, 0, 0));
JPanel panel = new JPanel();
panel_1.add(panel);
JButton jbNum = new JButton("得到一个随机数");
panel.add(jbNum);
JPanel panel_2 = new JPanel();
panel_1.add(panel_2);
label = new JLabel("");
label.setOpaque(true);
label.setBackground(Color.CYAN);
panel_2.add(label);
JPanel panel_3 = new JPanel();
panel_1.add(panel_3);
jtfInput = new JTextField();
panel_3.add(jtfInput);
jtfInput.setColumns(10);
JButton jbOk = new JButton("确定");
jbOk.setEnabled(false);
panel_3.add(jbOk);
jbNum.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num = (int) (Math.random() * 10);// 生成随即数
times = 0; // 猜测次数归零
label.setText("随机数已经生成范围0~9");
jtfInput.setText(null);// 输入框清空
jbOk.setEnabled(true);// 按钮恢复可用
System.out.println(num);
}
});
jbOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int x;
try {
x = Integer.parseInt(jtfInput.getText());// 取得输入框的数字 进行比较
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, "输入格式错误!请输入数字", "提示", JOptionPane.WARNING_MESSAGE);
return;//输入字母等非整数,直接返回
}
if (x == num) {
JOptionPane.showMessageDialog(null, "厉害,猜对了~!");
jbOk.setEnabled(false);//按钮设置为不可用
return;//猜对了也返回
} else if (x < num) {
JOptionPane.showMessageDialog(null, "你猜小了", "提示", JOptionPane.WARNING_MESSAGE);
} else if (x > num) {
JOptionPane.showMessageDialog(null, "你猜大了", "提示", JOptionPane.WARNING_MESSAGE);
}
times++;
if (times >= MAX_TIMES) {
JOptionPane.showMessageDialog(null, "尝试次数过多失败", "提示", JOptionPane.WARNING_MESSAGE);
jbOk.setEnabled(false);//按钮设置为不可用
return;// 猜错次数太多也返回
}
}
});
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询