单击按钮时java将JLabel转换为计时器
在我的应用程序中,我正在创建一个timerLabel和timerPanel,如下所示:
// Add timer panel
JPanel timerPanel = new JPanel();
timerPanel.setBorder(new EmptyBorder(0, 0, 0, 0));
timerPanel.setBackground(new Color(0x757575));
c.gridx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(0,0,0,20);
c.gridy = 0;
centerPanel.add(timerPanel, c);
// Add timer label
JLabel timerLabel = new JLabel("00:00", SwingConstants.RIGHT);
timerLabel.setForeground(Color.black);
timerLabel.setFont(new Font("Serif", Font.BOLD, 30));
timerLabel.setHorizontalAlignment(JLabel.RIGHT);
c.gridx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridy = 0;
timerLabel.setForeground(Color.white);
timerPanel.add(timerLabel, c);
我想让计时器从60秒开始倒数计时,只要用户单击start,然后重新启动按钮。下面是我实现的ActionListener。现在我不确定如何做到这一点:
private class ButtonHandler implements ActionListener {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
// The text from the button that the user clicked.
String cmd = e.getActionCommand();
// Respond to Quit button by ending the program.
if (cmd.equals(GuiText.START.toString())) {
startGame();
// start the timer here
} else if (cmd.equals(GuiText.PREVIOUS.toString())) {
QuestionList.selectRandomQuestion();
questionLabel.setText(message);
// reset the timer here
} else if (cmd.equals(GuiText.NEXT.toString())) {
QuestionList.selectRandomQuestion();
questionLabel.setText(message);
// reset the timer here
} else {
textArea.setText(cmd);
}
// Causes the display to be redrawn, to show any changes made.
display.repaint();
}
}
最后,我需要一种方法来跟踪计时器何时归零,以及在它不能调用方法时“做点什么”?我怎样才能做到这一点?我的完整代码可以在这里找到(上下文):https://pastebin.com/44XWxTQt。我感谢你的时间和帮助
# 1 楼答案
任何涉及更新Swing组件的内容都应该围绕
javax.swing.Timer
进行。这有start()
/stop()
方法可以在单击按钮时调用。它还可以通过构造函数配置为每秒调用自己的actionPerformed
方法(因此可以更新JLabel并重新绘制)https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html