一个猜数字的小游戏,要求添加计时器,下面是我的代码求大佬分析
package bianxie;import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class GuessNumber extends JFrame {
private JButton btn1;
private JButton btn2;
private JTextField jttime;
private JLabel jlfanwei;
private JLabel jltime;
private JLabel jlnum;
private JTextField jtffanwei;
private JTextField jtfnum;
private Timer tmr;
int guessNumber=0;
int max=100;
int min=1;
int haomiao=1000;
GuessNumber() {
super();
jttime = new JTextField("0",14);
jltime =new JLabel("时 间:");
jlnum = new JLabel("猜一猜:");
jtfnum = new JTextField(14);
jlfanwei=new JLabel("范 围:");
jtffanwei = new JTextField("请猜一个范围1-100的数字",14);
btn1 = new JButton("开始");
btn2 = new JButton("确定");
setLayout(new FlowLayout());
add(jltime);
add(jttime);
add(jlfanwei);
add(jtffanwei);
add(jlnum);
add(jtfnum);
add(btn1);
add(btn2);
setSize(230,170);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
btn1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == btn1) {
jttime.setText("0");
tmr.start();
} else {
int t;
t = Integer.parseInt(jltime.getText());
t++;
jltime.setText("" + t);
}
}
});
btn2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int num = (int) (Math.random() * 100) + 1;
if (guessNumber > num) {
max = guessNumber;
jtffanwei.setText("你猜大了!");
} else if (guessNumber < num) {
min = guessNumber;
jtffanwei.setText("你猜小了!");
}
}
});
}
public static void main(String[] args) {
GuessNumber c = new GuessNumber();
}
}