What I am trying to do:
I am trying to make a basic timer in java.
What approach I am following:
I am using Thread.sleep(1000) to make the main thread sleep for 1 second and as soon the Thread awakes the seconds field in the code increments by 1 and there is normal mathematics for minutes and hours.
The code itself:
public class a extends javax.swing.JFrame {
javax.swing.JTextField text,minute,starter,hours;
a() {
super("Timer!");
try{
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
} finally {
this.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER,20,20));
text = new javax.swing.JTextField();
hours = new javax.swing.JTextField();
hours.setPreferredSize(new java.awt.Dimension(25,25));
this.add(hours);
minute = new javax.swing.JTextField();
minute.setPreferredSize(new java.awt.Dimension(25,25));
javax.swing.JButton starter = new javax.swing.JButton("Start!");
this.add(minute);
text.setPreferredSize(new java.awt.Dimension(25,25));
this.add(text);
starter.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseReleased(java.awt.event.MouseEvent e) {
timer();
}
});
this.add(starter);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
text.setEditable(false);
text.setText("0");
minute.setEditable(false);
hours.setEditable(false);
minute.setText("0");
hours.setText("0");
}
}
private void timer() {
while(true) {
try {
Thread.sleep(1000);
int i = Integer.parseInt(text.getText());
i++;
text.setText(String.valueOf(i%60));
if(i==60) {
i = Integer.parseInt(minute.getText());
i++;
minute.setText(String.valueOf(i));
if(i==60) {
minute.setText("0");
int number = Integer.parseInt(hours.getText());
hours.setText(String.valueOf(++number));
}
}
} catch(Exception e) {
text.setText("crap!");
}
}
}
public static void main(String args[]){
a o = new a();
}
}
My Problem
My problem or question is that when I had not used the JButton starter and was just calling the timer() method inside the constructor, the timer worked like a charm, but when I am using the JButton and have put the timer() call in its event listener to start the timer as per requirement the application just freezes and nothing happens.
Like I mentioned above, if I just call timer inside the constructor and remove the JButton from the application everything works fine. But when using the JButton (in order to manually start the timer), the app just freezes.
Edit:
I am sorry! I forgot to mention when the app freezes it freezes upon clicking the JButton.
Edit:
This question is not a duplicate of the other question as the question is about how to create a timer in java, I never asked for that! I know that, What I asked in my question was what mistake I am making in my code, which one of the answers explains very well. I never asked the question "how to create timer in java".