package Mine;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GuessNumber extends JFrame implements ActionListener {
JPanel p1;
JButton btn1, btn2;
JLabel Lb1, Lb2, Lb3;
JLabel Lalimage;
JTextField text;
JTextArea area;
ImageIcon image;
ImageIcon image1 = new ImageIcon("img/我猜.jpg"), image2 = new ImageIcon(
"img/开始猜.jpg"), image3 = new ImageIcon("img/猜错了.jpg"),
image4 = new ImageIcon("img/猜对了.gif");
int number;
boolean flat = false;//是否已生成随机数
/**
* @param args
*/
public GuessNumber() {
try {
setTitle("猜数字");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
setLayout(null);// 先设置null,否则不显示
setSize(320, 260);
setLocationRelativeTo(null);// 界面位置
getContentPane().setBackground(Color.GRAY);// 一定要加getContentPane().
p1 = new JPanel();
p1.setBackground(Color.LIGHT_GRAY);
p1.setBounds(0, 0, 320, 100);
p1.setLayout(null);
add(p1);
btn1 = new JButton("生成随机数");
btn1.setBounds(200, 20, 100, 25);
btn1.addActionListener(this);
p1.add(btn1);
btn2 = new JButton("确定");
btn2.setBounds(200, 50, 100, 25);
btn2.addActionListener(this);
p1.add(btn2);
Lb1 = new JLabel("先选择一个随机数");
Lb1.setForeground(Color.BLUE);
Lb1.setBounds(40, 20, 110, 23);
p1.add(Lb1);
Lb2 = new JLabel("然后输入推测数字(1~100)");
Lb2.setForeground(Color.BLUE);
Lb2.setBounds(20, 35, 150, 23);
p1.add(Lb2);
text = new JTextField("0");
text.setForeground(Color.magenta);
text.setBounds(40, 60, 110, 23);
p1.add(text);
Lb3 = new JLabel("未生成随机数");
Lb3.setForeground(Color.red);
Lb3.setBackground(Color.gray);
Lb3.setBounds(20, 160, 120, 23);
add(Lb3);
area = new JTextArea("我猜!我猜!我猜猜猜!");
area.setForeground(Color.green);
area.setBackground(Color.gray);
area.setFont(new Font("宋体", Font.BOLD, 13));
area.setEditable(false);
area.setBounds(20, 130, 150, 25);
add(area);
Lalimage = new JLabel();
Lalimage.setBounds(180, 101, 128, 128);
add(Lalimage);
//Lalimage.setIcon(image1);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn1) {
number = (int) (Math.random() * 100) + 1;
Lb3.setText("已生成随机数");
area.setText("我猜!我猜!我猜猜猜!");
Lalimage.setIcon(image2);
flat = true;//已生成随机数
}
else if (e.getSource() == btn2) {
int guess = 0;
try {
guess = Integer.parseInt(text.getText());
if (flat == false) {
area.setText(" 没选你就猜,败RP!");
return;
}
else {
if (guess == number) {
area.setText(" 猜对了!就是" + number);
flat = false;
Lb3.setText("未生成随机数");
Lalimage.setIcon(image1);
}
else if (guess > number) {
area.setText(" 猜大了!");
text.setText(null);
Lalimage.setIcon(image3);
}
else if (guess < number) {
area.setText("猜小了!");
text.setText(null);
Lalimage.setIcon(image4);
}
}
}
catch (NumberFormatException event) {
event.printStackTrace();//
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
GuessNumber gn = new GuessNumber();
gn.setVisible(true);
}
}
|
|