Конвертировать JLabel в таймер при нажатии кнопки - PullRequest
0 голосов
/ 27 октября 2019

В моем приложении я создаю 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. Я ценю ваше время и помощь.

1 Ответ

1 голос
/ 27 октября 2019

Все, что связано с обновлением компонентов Swing, должно вращаться вокруг javax.swing.Timer. У этого есть start() / stop() методы для вызова ваших нажатий кнопок. Он также настраивается через конструктор для вызова своего собственного метода actionPerformed каждую секунду (поэтому вы можете обновить JLabel и перекрасить).

https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html

...