I'm trying to start a Timer after a button is pressed.
The following code without a button works
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("test");
}
});
timer.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
However when I put it inside a button
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("test");
}
});
timer.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
It does not print anything when the button is pressed.
I thought this occurred because the main thread ends, so I tried adding a while (true) at the end, but it did not change anything.
Thanks