GuessNumber Java实现
JAVA课后作业
/*
* 编写一个猜数程序,该程序随机在1到1000的范围中选择一个供用户猜测的整数。
* 界面上提供一个文本框来接收用户输入的猜测的数,
* 如果用户猜得太大,则背景变为红色,如果猜得太小,背景变为蓝色。
* 用户猜对后,文本框变为不可编辑,同时提示用户猜对了。
* 界面上提供一个按钮,使用户可以重新开始这个游戏。
* 在界面上还需显示用户猜测的次数。示例输出如下图所示。
*/
package GuessNumber;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class GuessNumber {
private JFrame frame;
private JTextField textfield; //文本框
private JButton button1,button2,button3; //按钮
private JLabel label1,label2,label3;
static int source = 0;
static Random rand = new Random();
private int count = 0;
public GuessNumber(){
//添加组件
frame = new JFrame("Guess Number");
JPanel panel1,panel2,panel3;
//设置面板的布局
panel1 = new JPanel();
panel1.setLayout(new FlowLayout(FlowLayout.LEFT));
panel2 = new JPanel();
panel2.setLayout(new FlowLayout(FlowLayout.LEFT,40,20));
panel3 = new JPanel();
panel3.setLayout(new FlowLayout(FlowLayout.LEFT,40,20));
//panel1
label1=new JLabel("你已经猜了0次");
panel1.add(label1);
//panel2
label2=new JLabel("输入猜测的数");
panel2.add(label2);
textfield = new JTextField(10);
panel2.add(textfield);
label3=new JLabel();
panel2.add(label3);
//panel3
button1 = new JButton("确认");
button2 = new JButton("重新开始");
button3 = new JButton("退出");
panel3.add(button1);
panel3.add(button2);
panel3.add(button3);
frame.setLayout(new GridLayout(3, 1));
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
//设置监听事件
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
count++;
label1.setText("你已经猜了"+count+"次");
int num = Integer.parseInt(textfield.getText());
if(num == source){
label3.setText("猜测正确!");
textfield.setEditable(false);
textfield.setBackground(frame.getBackground());
}
else if(num > source){
label3.setText("太大");
textfield.setBackground(Color.red);
}
else{
label3.setText("太小");
textfield.setBackground(Color.blue);
}
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
count=0;
label1.setText("你已经猜了"+count+"次");
while((source=rand.nextInt(1000))==0);
textfield.setEditable(true);
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
frame.setSize(700, 400);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
}
public static void main(String[] args) {
new GuessNumber();
source=rand.nextInt(1000);
while(source==0);
}
}