I'm trying to make a timer application in Java but during the counting process, it won't execute main (also opening the window) until the counter finishes. This is what I mean:
long timeElapsed = 0;
long timeStart = System.currentTimeMillis();
for (long counter=0;counter<5;++counter) {
TimeUnit.SECONDS.sleep(1);
timeElapsed = (System.currentTimeMillis() - timeStart)/1000;
display.setText(Long.toString(timeElapsed));
}
String myString = Long.toString(timeElapsed);
The program won't make a window until the for
statement is finished which is bad because it doesnt display the time until its done which is not what im aiming for.
Is there any way to window update while it is running so that the program displays the time elapsed?
My code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.util.concurrent.TimeUnit;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JButton;
public class TimerGUI {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TimerGUI window = new TimerGUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* @throws InterruptedException
*/
public TimerGUI() throws InterruptedException {
initialize();
}
/**
* Initialize the contents of the frame.
* @throws InterruptedException
*/
private void initialize() throws InterruptedException {
JLabel display = new JLabel("a");
// TIME
long timeElapsed = 0;
long timeStart = System.currentTimeMillis();
for (long counter=0;counter<5;++counter) {
TimeUnit.SECONDS.sleep(1);
timeElapsed = (System.currentTimeMillis() - timeStart)/1000;
display.setText(Long.toString(timeElapsed));
}
String myString = Long.toString(timeElapsed);
//WINDOW
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
// LABEL
//display = new JLabel(myString);
display.setBounds(165, 64, 89, 54);
frame.getContentPane().add(display);
//BUTTON
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(165, 169, 89, 32);
frame.getContentPane().add(btnNewButton);
}
}
Note: Im not using the Button part of program yet and also the code Im trying to fix is in the method Initialize()
.