I have an issue with Java thread. Actually I've created a timer but whenever I click the start button more than once the program starts counting fast!!
I want my program to start from zero when I press start the second time with the initial speed.
I tried to fix that but I couldn't find a solution.
Why is this happening, is it something internal to JVM?
here is my code..
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;;
public class Timer extends JFrame implements ActionListener
{
private JPanel panel1,panel2;
private JButton button;
private JLabel label;
private int second = 0;
private int mint = 0;
boolean flage = true;
public Timer()
{
super("Timer");
setSize(300,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setResizable(false);
label = new JLabel();
panel1 = new JPanel(new FlowLayout());
panel1.add(label);
button = new JButton("Start");
panel2 = new JPanel(new FlowLayout());
panel2.add(button);
button.addActionListener(this);
panel1.setBackground(Color.white);
panel2.setBackground(Color.white);
add("Center",panel1);
add("South",panel2);
setVisible(true);
}
public void paint(Graphics g)
{
super.paint(g);
Font myFont = new Font("Elephant", Font.BOLD,34);
g.setFont(myFont);
g.setColor(Color.black);
g.drawString(String.format("%02d",mint)+":"+String.format("%02d", second), 90, 80);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button)
{
if(flage)
{
mythread a = new mythread();
a.start();
}
}
}
class mythread extends Thread
{
public void run()
{
for(int i=0;i<60;i++)
{
for(int j=0;j<60;j++)
{
second++;
if(second==60)
{
second=0;
mint++;
}
repaint();
doNothing(1000);
}
repaint();
}
}
public void doNothing(int a)
{
try
{
Thread.sleep(a);
}
catch(Exception e)
{
}
}
}
public static void main(String[]args)
{
new Timer();
}
}
Thanks