import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*This program is a geme for guessing a number which is between 1 and 1000.
*2008-10-29
*@author XYX
*/
public class GuessNumTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
GuessFrame frame =new GuessFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
}
});
}
}
class GuessFrame extends JFrame
{
public GuessFrame()
{
setTitle("猜数游戏");
setSize(300,200);
//计数板
count=0;
countPanel=new JPanel();
label1=new JLabel("你已经猜了0次");
countPanel.add(label1);
add(countPanel, BorderLayout.NORTH);
//输入板
num=(int)(Math.random()*1000+1);
inputPanel=new JPanel();
label2=new JLabel("输入猜测的数");
label3=new JLabel("");
input=new JTextField(4);
inputPanel.add(label2);
inputPanel.add(input);
inputPanel.add(label3);
add(inputPanel, BorderLayout.CENTER);
//按钮板
buttonPanel = new JPanel();
//确认按钮
JButton yesButton=new JButton("确认");
buttonPanel.add(yesButton);
yesButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
count++;//已猜次数加1
label1.setText("你已经猜了"+count+"次");
int inNum=Integer.parseInt(input.getText());//将用户输入变为整数
if(inNum>num)//猜得太大
{
countPanel.setBackground(Color.RED);//背景变为红色
inputPanel.setBackground(Color.RED);
buttonPanel.setBackground(Color.RED);
label3.setText("太大");//显示"太大"
}
else if(inNum{
countPanel.setBackground(Color.BLUE);//背景变为蓝色
inputPanel.setBackground(Color.BLUE);
buttonPanel.setBackground(Color.BLUE);
label3.setText("太小");//显示"太小"
}
else//猜对了
{
input.setEditable(false);//文本框变为不可编辑
countPanel.setBackground(Color.WHITE);//背景变为白色
inputPanel.setBackground(Color.WHITE);
buttonPanel.setBackground(Color.WHITE);
label3.setText("猜对了");//显示"猜对了"
}
}
});
//重新开始按钮
JButton resButton=new JButton("重新开始");
buttonPanel.add(resButton);
resButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
count=0;//已猜次数置0
label1.setText("你已经猜了0次");
input.setText("");
label3.setText("");
countPanel.setBackground(Color.WHITE);//背景变为白色
inputPanel.setBackground(Color.WHITE);
buttonPanel.setBackground(Color.WHITE);
num=(int)(Math.random()*1000+1);//重新生成随机数
input.setEditable(true);//文本框变为可编辑
}
});
//退出按钮
JButton exitButton=new JButton("退出");
buttonPanel.add(exitButton);
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);//退出
}
});
add(buttonPanel, BorderLayout.SOUTH);
}
private JLabel label1;//显示标签,用于显示已猜次数
private JLabel label2;//显示标签,显示"输入猜测的数"
private JLabel label3;//显示标签,用于显示对输入的处理结果
private JTextField input;//输入框,用于接收用户的输入
private JPanel countPanel;//计数板
private JPanel inputPanel;//输入板
private JPanel buttonPanel;//按钮板
private int count;//已猜次数
private int num;//要猜的数
}