在我的应用程序中,我正在如下创建一个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秒开始倒计时。以下是我实现的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。感谢您的时间和帮助。
答案 0 :(得分:1)
任何涉及更新Swing组件的事情都应该围绕javax.swing.Timer
进行。它具有start()
/ stop()
方法来调用按钮单击。还可以通过构造函数将其配置为每秒调用其自己的actionPerformed
方法(这样您就可以更新JLabel并重新绘制)。
https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html