java 用图形化界面编写一个猜数游戏
发布网友
发布时间:2022-05-06 18:16
我来回答
共2个回答
热心网友
时间:2022-07-01 17:24
效果图
一个比较简单的代码, 供参考 ,可以根据自己的需求, 在进行修改
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;
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("确定");
panel_3.add(jbOk);
jbNum.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
num = (int)(Math.random()*10);//生成随即数
label.setText("随机数已经生成范围0~9");
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, "sorry,输入错误!");
return;
}
if(x==num){
JOptionPane.showMessageDialog(null, "厉害,猜对了~!");
}else if(x<num){
JOptionPane.showMessageDialog(null, "你猜小了", "提示",JOptionPane.WARNING_MESSAGE);
}else if(x>num) {
JOptionPane.showMessageDialog(null, "你猜大了", "提示",JOptionPane.WARNING_MESSAGE);
}
}
});
}
}
热心网友
时间:2022-07-01 17:25
问题不太详细