如何在 Java 中暂停和恢复计时器
How to pause and resum a timer in Java
我有一个小游戏,我需要在用户按下暂停按钮时暂停计时器,然后在用户按下恢复按钮时恢复计时器并继续增加秒数。
我研究了很多,尝试了不同的解决方案,但 none 对我有用。
你能帮我实现这个功能吗?
这是我的代码:
public class App {
private JTextField timerHours;
private JTextField timerMinutes;
private JTextField timerSeconds;
private Timer timer = new Timer();
private long timeElapsedInSeconds = 0;
private JButton playButton;
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
App window = new App();
} catch (Exception e) {
e.printStackTrace();
}
});
}
private App() {
initializeWindow();
createTimer();
}
private void createTimer() {
timer.schedule(new TimerTask() {
@Override
public void run() {
timeElapsedInSeconds += 1;
System.out.println("Elapsed seconds: " + timeElapsedInSeconds);
timerSeconds.setText(String.valueOf(timeElapsedInSeconds % 60));
timerMinutes.setText(String.valueOf((timeElapsedInSeconds / 60) % 60));
timerHours.setText(String.valueOf((timeElapsedInSeconds / 60) / 60));
}
}, 1000, 1000);
}
private void initializeWindow() {
JPanel bottom_panel = new JPanel();
bottom_panel.setLayout(null);
// Create Pause button
JButton pauseButton = new JButton("Pause");
pauseButton.setBounds(10, 20, 90, 25);
pauseButton.addActionListener(actionEvent -> {
// Pause the game
timer.cancel();
playButton.setEnabled(true);
pauseButton.setEnabled(false);
});
bottom_panel.add(pauseButton);
// Create Play button
playButton = new JButton("Play");
playButton.setBounds(110, 20, 90, 25);
playButton.setEnabled(false);
playButton.addActionListener(actionEvent -> {
// Resume the game and continue the timer from the value saved in `timeElapsedInSeconds`
playButton.setEnabled(false);
pauseButton.setEnabled(true);
});
bottom_panel.add(playButton);
}
感谢阅读本文。
尝试使用 Swing timer.
private void createTimer() {
timer = new Timer(1000, (ae)->
{
timeElapsedInSeconds += 1;
System.out.println(
"Elapsed seconds: " + timeElapsedInSeconds);
timerSeconds.setText(
String.valueOf(timeElapsedInSeconds % 60));
timerMinutes.setText(String
.valueOf((timeElapsedInSeconds / 60) % 60));
timerHours.setText(String
.valueOf((timeElapsedInSeconds / 60) / 60));
});
timer.setDelay(1000);
timer.start(); // or start it elsewhere
}
然后您可以使用stop()
和start()
方法来暂停和恢复动作。查看 javaDocs 了解更多详情。
这是完整的代码,谁会需要这样的东西:
import javax.swing.*;
import java.awt.*;
public class App {
private JFrame gameFrame;
private JTextField timerHours;
private JTextField timerMinutes;
private JTextField timerSeconds;
private Timer timer;
private long timeElapsedInSeconds = 0;
private JButton playButton;
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
App window = new App();
window.gameFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
private App() {
initializeWindow();
createTimer();
}
private void createTimer() {
timer = new Timer(1000, (ae) ->
{
timeElapsedInSeconds += 1;
System.out.println("Elapsed seconds: " + timeElapsedInSeconds);
timerSeconds.setText(String.valueOf(timeElapsedInSeconds % 60));
timerMinutes.setText(String.valueOf((timeElapsedInSeconds / 60) % 60));
timerHours.setText(String.valueOf((timeElapsedInSeconds / 60) / 60));
});
timer.setDelay(1000);
timer.start(); // or start it elsewhere
}
private void initializeWindow() {
// Create main window
gameFrame = new JFrame();
gameFrame.setFocusable(true);
gameFrame.requestFocus();
gameFrame.setFocusTraversalKeysEnabled(false);
gameFrame.setTitle("My Game");
gameFrame.setResizable(false);
gameFrame.setBounds(100, 100, 700, 600);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create right panel of main window which will contain the Digital Timer, Console buttons etc
JPanel right_panel = new JPanel();
right_panel.setLayout(null);
// Create bottom panel of main window which will contain the buttons
JPanel bottom_panel = new JPanel();
bottom_panel.setLayout(null);
// Create Digital Timer
JPanel digital_timer = new JPanel();
digital_timer.setLayout(new FlowLayout());
digital_timer.setBounds(30, 10, 100, 60);
JLabel timer_label = new JLabel("DIGITAL TIMER");
timer_label.setForeground(Color.black);
digital_timer.add(timer_label);
// Create hours textField for digital timer
timerHours = new JTextField("00");
timerHours.setEditable(false);
timerHours.setBackground(Color.black);
timerHours.setForeground(Color.white);
digital_timer.add(timerHours);
JLabel timer_label2 = new JLabel(":");
timer_label2.setForeground(Color.white);
digital_timer.add(timer_label2);
// Create minutes textField for digital timer
timerMinutes = new JTextField("00");
timerMinutes.setEditable(false);
timerMinutes.setBackground(Color.black);
timerMinutes.setForeground(Color.white);
digital_timer.add(timerMinutes);
JLabel timer_label3 = new JLabel(":");
timer_label3.setForeground(Color.white);
digital_timer.add(timer_label3);
// Create seconds textField for digital timer
timerSeconds = new JTextField("00");
timerSeconds.setEditable(false);
timerSeconds.setBackground(Color.black);
timerSeconds.setForeground(Color.white);
digital_timer.add(timerSeconds);
right_panel.add(digital_timer);
// Create Pause button
JButton pauseButton = new JButton("Pause");
pauseButton.setBounds(10, 20, 90, 25);
pauseButton.addActionListener(actionEvent -> {
// Pause the game
timer.stop();
playButton.setEnabled(true);
pauseButton.setEnabled(false);
});
bottom_panel.add(pauseButton);
// Create Play button
playButton = new JButton("Play");
playButton.setBounds(110, 20, 90, 25);
playButton.setEnabled(false);
playButton.addActionListener(actionEvent -> {
// Run the game
timer.start();
playButton.setEnabled(false);
pauseButton.setEnabled(true);
});
bottom_panel.add(playButton);
// Create a group of layouts (Container) where to put all frames and panels used in this app.
GroupLayout groupLayout = new GroupLayout(gameFrame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
// Set width dimensions for right panel
.addComponent(right_panel, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE))
// Set width dimensions for bottom panel
.addComponent(bottom_panel, GroupLayout.PREFERRED_SIZE, 650, GroupLayout.PREFERRED_SIZE)
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
// Set height dimensions for right panel
.addComponent(right_panel, GroupLayout.PREFERRED_SIZE, 500, GroupLayout.PREFERRED_SIZE))
// Set height dimensions for bottom panel
.addComponent(bottom_panel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
gameFrame.getContentPane().setLayout(groupLayout);
}
}
我有一个小游戏,我需要在用户按下暂停按钮时暂停计时器,然后在用户按下恢复按钮时恢复计时器并继续增加秒数。 我研究了很多,尝试了不同的解决方案,但 none 对我有用。 你能帮我实现这个功能吗? 这是我的代码:
public class App {
private JTextField timerHours;
private JTextField timerMinutes;
private JTextField timerSeconds;
private Timer timer = new Timer();
private long timeElapsedInSeconds = 0;
private JButton playButton;
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
App window = new App();
} catch (Exception e) {
e.printStackTrace();
}
});
}
private App() {
initializeWindow();
createTimer();
}
private void createTimer() {
timer.schedule(new TimerTask() {
@Override
public void run() {
timeElapsedInSeconds += 1;
System.out.println("Elapsed seconds: " + timeElapsedInSeconds);
timerSeconds.setText(String.valueOf(timeElapsedInSeconds % 60));
timerMinutes.setText(String.valueOf((timeElapsedInSeconds / 60) % 60));
timerHours.setText(String.valueOf((timeElapsedInSeconds / 60) / 60));
}
}, 1000, 1000);
}
private void initializeWindow() {
JPanel bottom_panel = new JPanel();
bottom_panel.setLayout(null);
// Create Pause button
JButton pauseButton = new JButton("Pause");
pauseButton.setBounds(10, 20, 90, 25);
pauseButton.addActionListener(actionEvent -> {
// Pause the game
timer.cancel();
playButton.setEnabled(true);
pauseButton.setEnabled(false);
});
bottom_panel.add(pauseButton);
// Create Play button
playButton = new JButton("Play");
playButton.setBounds(110, 20, 90, 25);
playButton.setEnabled(false);
playButton.addActionListener(actionEvent -> {
// Resume the game and continue the timer from the value saved in `timeElapsedInSeconds`
playButton.setEnabled(false);
pauseButton.setEnabled(true);
});
bottom_panel.add(playButton);
}
感谢阅读本文。
尝试使用 Swing timer.
private void createTimer() {
timer = new Timer(1000, (ae)->
{
timeElapsedInSeconds += 1;
System.out.println(
"Elapsed seconds: " + timeElapsedInSeconds);
timerSeconds.setText(
String.valueOf(timeElapsedInSeconds % 60));
timerMinutes.setText(String
.valueOf((timeElapsedInSeconds / 60) % 60));
timerHours.setText(String
.valueOf((timeElapsedInSeconds / 60) / 60));
});
timer.setDelay(1000);
timer.start(); // or start it elsewhere
}
然后您可以使用stop()
和start()
方法来暂停和恢复动作。查看 javaDocs 了解更多详情。
这是完整的代码,谁会需要这样的东西:
import javax.swing.*;
import java.awt.*;
public class App {
private JFrame gameFrame;
private JTextField timerHours;
private JTextField timerMinutes;
private JTextField timerSeconds;
private Timer timer;
private long timeElapsedInSeconds = 0;
private JButton playButton;
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
App window = new App();
window.gameFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
private App() {
initializeWindow();
createTimer();
}
private void createTimer() {
timer = new Timer(1000, (ae) ->
{
timeElapsedInSeconds += 1;
System.out.println("Elapsed seconds: " + timeElapsedInSeconds);
timerSeconds.setText(String.valueOf(timeElapsedInSeconds % 60));
timerMinutes.setText(String.valueOf((timeElapsedInSeconds / 60) % 60));
timerHours.setText(String.valueOf((timeElapsedInSeconds / 60) / 60));
});
timer.setDelay(1000);
timer.start(); // or start it elsewhere
}
private void initializeWindow() {
// Create main window
gameFrame = new JFrame();
gameFrame.setFocusable(true);
gameFrame.requestFocus();
gameFrame.setFocusTraversalKeysEnabled(false);
gameFrame.setTitle("My Game");
gameFrame.setResizable(false);
gameFrame.setBounds(100, 100, 700, 600);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create right panel of main window which will contain the Digital Timer, Console buttons etc
JPanel right_panel = new JPanel();
right_panel.setLayout(null);
// Create bottom panel of main window which will contain the buttons
JPanel bottom_panel = new JPanel();
bottom_panel.setLayout(null);
// Create Digital Timer
JPanel digital_timer = new JPanel();
digital_timer.setLayout(new FlowLayout());
digital_timer.setBounds(30, 10, 100, 60);
JLabel timer_label = new JLabel("DIGITAL TIMER");
timer_label.setForeground(Color.black);
digital_timer.add(timer_label);
// Create hours textField for digital timer
timerHours = new JTextField("00");
timerHours.setEditable(false);
timerHours.setBackground(Color.black);
timerHours.setForeground(Color.white);
digital_timer.add(timerHours);
JLabel timer_label2 = new JLabel(":");
timer_label2.setForeground(Color.white);
digital_timer.add(timer_label2);
// Create minutes textField for digital timer
timerMinutes = new JTextField("00");
timerMinutes.setEditable(false);
timerMinutes.setBackground(Color.black);
timerMinutes.setForeground(Color.white);
digital_timer.add(timerMinutes);
JLabel timer_label3 = new JLabel(":");
timer_label3.setForeground(Color.white);
digital_timer.add(timer_label3);
// Create seconds textField for digital timer
timerSeconds = new JTextField("00");
timerSeconds.setEditable(false);
timerSeconds.setBackground(Color.black);
timerSeconds.setForeground(Color.white);
digital_timer.add(timerSeconds);
right_panel.add(digital_timer);
// Create Pause button
JButton pauseButton = new JButton("Pause");
pauseButton.setBounds(10, 20, 90, 25);
pauseButton.addActionListener(actionEvent -> {
// Pause the game
timer.stop();
playButton.setEnabled(true);
pauseButton.setEnabled(false);
});
bottom_panel.add(pauseButton);
// Create Play button
playButton = new JButton("Play");
playButton.setBounds(110, 20, 90, 25);
playButton.setEnabled(false);
playButton.addActionListener(actionEvent -> {
// Run the game
timer.start();
playButton.setEnabled(false);
pauseButton.setEnabled(true);
});
bottom_panel.add(playButton);
// Create a group of layouts (Container) where to put all frames and panels used in this app.
GroupLayout groupLayout = new GroupLayout(gameFrame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
// Set width dimensions for right panel
.addComponent(right_panel, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE))
// Set width dimensions for bottom panel
.addComponent(bottom_panel, GroupLayout.PREFERRED_SIZE, 650, GroupLayout.PREFERRED_SIZE)
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
// Set height dimensions for right panel
.addComponent(right_panel, GroupLayout.PREFERRED_SIZE, 500, GroupLayout.PREFERRED_SIZE))
// Set height dimensions for bottom panel
.addComponent(bottom_panel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
gameFrame.getContentPane().setLayout(groupLayout);
}
}