[英]Convert JLabel to timer on button click
Within my application, I am creating a timerLabel and timerPanel as follows:在我的应用程序中,我正在创建一个 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);
I would like for the timer to start counting down from 60 seconds whenever the user clicks on the Start, and restarted the button.每当用户单击“开始”并重新启动按钮时,我希望计时器从 60 秒开始倒计时。 Below is the ActionListener I have implemented.
下面是我实现的 ActionListener。 Right now I am unsure about how to do this:
现在我不确定如何做到这一点:
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();
}
}
Lastly I need a way of tracking when the timer gets to zero and "doing something" when it does beign able to call a method?最后,我需要一种方法来跟踪计时器何时归零并在它确实能够调用方法时“做某事”? How can I accomplish this?
我怎样才能做到这一点? My full code is available here (for context): https://pastebin.com/44XWxTQt .
我的完整代码可在此处获得(用于上下文): https://pastebin.com/44XWxTQt 。 I appreciate your time and help.
感谢您的时间和帮助。
Anything involving updating Swing components should revolve around javax.swing.Timer
.任何涉及更新 Swing 组件的事情都应该围绕
javax.swing.Timer
。 This has start()
/ stop()
methods to call on your button-clicks.这有
start()
/ stop()
方法来调用您的按钮点击。 It is also configurable via the constructor to call its own actionPerformed
method every second (so you can update the JLabel and repaint).它也可以通过构造函数配置为每秒调用它自己的
actionPerformed
方法(因此您可以更新 JLabel 并重新绘制)。
https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.