机数。后让用户输入数字并通知其输入的数字与随机数的差
距直到数字吻合为止。
Just do it!
//GuessNumber.java
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GuessNumber extends JFrame implements ActionListener
{
private JButton produceJB , okJB;
private JLabel inputJL , statusJL;
private JTextField inputJTF , statusJTF;
private JPanel inputJP , statusJP , buttonJP;
private Random r;
private int guessnum , inputnum , tempnum;
private boolean isproduce = false;
public GuessNumber()
{
super("猜数字");
produceJB = new JButton("生成");
okJB = new JButton("确定");
inputJL = new JLabel("输入");
statusJL = new JLabel("提示");
inputJTF = new JTextField(10);
statusJTF = new JTextField(10);
statusJTF.setEditable(false);
inputJP = new JPanel(new FlowLayout());
statusJP = new JPanel(new FlowLayout());
buttonJP = new JPanel(new FlowLayout());
inputJP.add(inputJL);
inputJP.add(inputJTF);
statusJP.add(statusJL);
statusJP.add(statusJTF);
buttonJP.add(produceJB);
buttonJP.add(okJB);
produceJB.addActionListener(this);
okJB.addActionListener(this);
JPanel jp = (JPanel)this.getContentPane();
jp.setLayout(new GridLayout(3,1));
jp.add(inputJP);
jp.add(statusJP);
jp.add(buttonJP);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(450,300);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("生成"))
{
isproduce = true;
r = new Random();
guessnum = r.nextInt()%500;
inputJTF.setText("");
statusJTF.setText("");
JOptionPane.showMessageDialog(null,
"已生成一个随机数",
"信息",
JOptionPane.INFORMATION_MESSAGE );
}
else if(str.equals("确定"))
{
if(isproduce != true)
{
JOptionPane.showMessageDialog(null,
"请按''生成''按钮生成一个随机数",
"错误",
JOptionPane.ERROR_MESSAGE);
}
else
{
try
{
inputnum = Integer.parseInt(inputJTF.getText());
}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(null,
"请输入一个整数",
"错误",
JOptionPane.ERROR_MESSAGE);
return;
}
tempnum = inputnum - guessnum;
if(tempnum > 0)
{
statusJTF.setText("高了");
}
if(tempnum < 0)
{
statusJTF.setText("低了");
}
else if(tempnum == 0)
{
statusJTF.setText("恭喜你!猜对了!");
isproduce = false;
}
}
}
}
public static void main(String[] args)
{
new GuessNumber();
}
}
[此贴子已经被作者于2006-1-29 15:18:55编辑过]