//代码写得不错,不过布局有点乱,呵呵,而且你可以设计当点到textfield
//的时候自动清除里面的字,这样会更方便一点
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class GuessNumber extends Frame{
private static GuessNumber mainFrame = new GuessNumber();
private static Button yes = new Button("确定输入");
private static Button reTry = new Button("重新测试");
private static Label lb = new Label("请输入你猜测的数字(0~100):");
private static Label ts = new Label("欢迎使用~~~~~");
private static Double r_num = new Double(Math.random()*100);
private static Integer num = new Integer(r_num.intValue());
private static int t_num;
private static TextField tf = new TextField("在这里输入数字",15);
private static String ct_img = "welcome.jpg";
//把count和ct都定义成static
static int count;
final static Label ct = new Label("你已经猜了:"+count);
public GuessNumber(){
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}
});
}
public static void main (String[] args) {
yes.addActionListener(new ButtonListener());
reTry.addActionListener(new ButtonListener());
System.out.println("Starting GussNumber...");
mainFrame.setBackground(Color.WHITE);
mainFrame.setSize(400,400);
mainFrame.setLayout(null);
mainFrame.setTitle("猜数字");
mainFrame.add(lb);
lb.setBounds(70,150,200,20);
mainFrame.add(tf);
tf.setBounds(270,150,100,20);
mainFrame.add(yes);
yes.setBounds(240,170,60,25);
mainFrame.add(ts);
ts.setBounds(70,130,200,20);
mainFrame.add(reTry);
reTry.setBounds(100,170,60,25);
mainFrame.add(ct);
ct.setBounds(70,300,200,20);
mainFrame.setResizable(true);
mainFrame.setVisible(true);
}
static class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if(event.getSource()==yes){
try{
t_num = Integer.parseInt(tf.getText());
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null,"请输入正常的数字!");
ct_img = "welcome.jpg";
r_num = new Double(Math.random()*100);
num = new Integer(r_num.intValue());
tf.setText("");
mainFrame.setSize(400,400);
}
if(t_num == num){
ct_img = "right.jpg";
ts.setText("答对啦! 恭喜你~");
//在这里可以直接加猜中了几次,然后显示
count++;
ct.setText("你已经猜了:"+count);
}
if(t_num > num){
ct_img = "tooBig.jpg";
ts.setText("大了点哦! 继续努力~");
}
if(t_num < num){
ct_img = "tooSmall.jpg";
ts.setText("试试换个大点的数字~");
}
}
if(event.getSource()==reTry){
r_num = new Double(Math.random()*100);
num = new Integer(r_num.intValue());
tf.setText("");
mainFrame.setSize(400,400);
}
}
}
}
代码写的非常混乱。
权宜之计的改法:
1 在GuessNumber类中添加成员变量,
private static int GuessCount =0;
private static Label DisplayCount=new Label(" ");
2 在actionPerformed中添加
GuessCount++;
DisplayCount.setText("Guessed "+GuessCount);
3 在actionPerformed中添加
GuessCount = 0;