我正在尝试构建一个国际象棋时钟来学习,但我被下面的代码困住了。我将像这样使用actionListener。当按下“白色”按钮时,blackTime 每秒减一,当按下“黑色”按钮时,whiteTime 每秒减一。
现在我的问题是找到一种方法来减少每秒的时间。我看到一些这样的问题,他们谈到了Timer类。我从未使用过它,我的理解是它需要一个 ActionListener。我已经在使用一个,所以我要添加另一个还是有更简单的方法?
谢谢!
public class ChessClock extends JFrame implements ActionListener {
JPanel p;
JButton b1,b2;
JLabel l1;
public ChessClock(){
super();
this.setVisible(true);
this.setSize(600,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int whiteTime = 59;
int blackTime = 59;
p = new JPanel(new GridBagLayout());
b1 = new JButton("White");
b2 = new JButton("Black");
l1 = new JLabel("00:" + whiteTime + " - " + "00:" + blackTime, SwingConstants.CENTER);
l1.setFont(new Font("Serif", Font.PLAIN, 85));
b1.setPreferredSize(new Dimension(200,100));
b2.setPreferredSize(new Dimension(200,100));
b1.addActionListener(this);
b2.addActionListener(this);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(40,40,40,40);
p.add(b1,c);
p.add(b2,c);
this.add(p, BorderLayout.SOUTH);
this.add(l1, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e){ //will later be used to switch between whiteTime - blackTime
String s = e.getActionCommand();
if(s == "White")
s = s;
if(s == "Black")
s = s;
}
}
最佳答案
来自Java Docs ,
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(blackTurn)
black--;
else if(whiteTurn)
white--;
}
};
new Timer(delay, taskPerformer).start();
我认为一般来说你应该避免使用Thread.sleep()
并使用内置的计时器类!带有 Thread.sleep()
的 while 循环将暂停线程并等待,而计时器则不会。
所以是的,创建另一个执行的操作!
关于java - 棋钟时间递减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24393803/