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<num)//猜得太小
{
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;//要猜的數
}