猜数游戏,随机产生一个整数,实现下列要求:
1.能够输入一个数判断其大小。
若数大于初始值,提示“ (输入的数)大了,请重新输入吧 ”,并且屏幕背景为粉红色;
若数小于初始值,提示“(输入的数) 小了,请重新输入吧 ”,并且背景为浅绿色;
当数等于时显示“ 恭喜您,答对了”。值不等时可以反复输入直到相等,相等时不可再输入。
2.设置“重置”命令按钮,随机产生一个新的整数。
代码实现:
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class ex3_4 extends JFrame implements ActionListener {
private JLabel shu;
private JTextField shuField;
// private JComboBox ;
private JButton confirm, reset;
String zhi;
int number = (int) (Math.random() * 1000 + 1);
public ex3_4(String title) {
super(title);
setSize(300, 180);// 设置窗体大小
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = size.width;
int screenHeight = size.height;
int x = (screenWidth - this.getWidth()) / 2;
int y = (screenHeight - this.getHeight()) / 2;
this.setLocation(x, y);// 屏幕居中显示
setDefaultCloseOperation(EXIT_ON_CLOSE);// 正常关闭窗体
setResizable(false); // 设置窗体大小不可改变
createUIElement();
shu = new JLabel("请输入您猜的数值 :");
shuField = new JTextField(20);
setLayout(null);
shu.setBounds(40, 30, 200, 20);
shuField.setBounds(160, 30, 70, 20);
// 将上述组件添加到顶层窗体中
add(shu);
add(shuField);
setVisible(true); // 显示窗体
}
public void reset() {
number = (int) (Math.random() * 1000 + 1);
}
public void createUIElement() {
JButton confirmBtn = new JButton("确认");
confirmBtn.setBounds(30, 100, 60, 20);
this.add(confirmBtn);
JButton resetBtn = new JButton("重置");
resetBtn.setBounds(180, 100, 60, 20);
this.add(resetBtn);
confirmBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getzhi();
guess();
}
private String getzhi() {
zhi = shuField.getText();
return zhi;
}
public void guess() {
Integer shuzhi = Integer.parseInt(zhi);
if (shuzhi == number) {
JOptionPane.showMessageDialog(null, "恭喜您,答对了是" + shuzhi, "提示", JOptionPane.PLAIN_MESSAGE);
Container con = getContentPane();
con.setBackground(Color.getHSBColor(13, 26, 39));
shuField.requestFocus();
} else if (shuzhi > number) {
Container con = getContentPane();
con.setBackground(Color.pink);
JOptionPane.showMessageDialog(null, shuzhi + "大了,请重新输入吧", "提示", JOptionPane.PLAIN_MESSAGE);
shuField.requestFocus();
shuField.setText("");
} else {
Container con = getContentPane();
con.setBackground(Color.getHSBColor(35, 454, 543));
JOptionPane.showMessageDialog(null, shuzhi + "小了,请重新输入吧", "提示", JOptionPane.PLAIN_MESSAGE);
shuField.requestFocus();
shuField.setText("");
}
}
});
resetBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shuField.setText("");
shuField.requestFocus();
reset();
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args) {
ex3_4 cai = new ex3_4("猜数游戏");
}
}