I created a game, and in my swing GUI I want to set a timer. The way I am doing this at the moment has a field with the current time, obtained with the help System.currentTimeMillis(), which gets its value when the game starts. In the method of my game, I put a field System.currentTimeMillis(); and he tells you the current time since the start of the game.
However, how to do this to update every second, say, so it JLabelwill have: timePassed: 0s, timePassed: 1s, etc. Keep in mind that I do not use threads in my game at any time.
EDIT: Thank you all for your kind suggestions. I used a combination of your answers, please give me some feedback.
I have jlabel as a field called time. (otherwise I can't handle it).
time = new JLabel("Time Passed: " + timePassed() + " sec");
panel_4.add(time);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
time.setText("Time Passed: " + timePassed() + " sec");
}
};
Timer timer = new Timer(1000, actionListener);
timer.start();
source
share