Pages

Java simple timer

Complete source code below will show you, how to create simple timer using java. Actually it has a problem. The problem that i mean is, it seem more slow than real timer.If you find how to solve it, i hope you can share with me by put a comment.

*******************************************************************
COMPLETE SOURCE CODE FOR : JavaSimpleTimer.java
*******************************************************************


import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class JavaSimpleTimer extends JPanel implements ActionListener
{
int miliseconds=0;
int seconds=0;
int minutes=0;

Timer myTimer;

Font timerFont=new Font("Verdana",Font.BOLD,24);

public JavaSimpleTimer()
{
myTimer=new Timer(10,this);

JFrame myFrame=new JFrame("Simple Timer");

myFrame.add(this);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(500,500);
myFrame.setVisible(true);

myTimer.setInitialDelay(0);
myTimer.start();
}

public void paint(Graphics g)
{
super.paint(g);
String mili=Integer.toString(miliseconds);
String sec=Integer.toString(seconds);
String min=Integer.toString(minutes);

if(mili.length()==1)
{
mili="0"+mili;
}
if(sec.length()==1)
{
sec="0"+sec;
}
if(min.length()==1)
{
min="0"+min;
}

g.setFont(timerFont);

g.drawString(min+" :",20,20);
g.drawString(sec+" :",80,20);
g.drawString(mili,140,20);
}

public void actionPerformed(ActionEvent event)
{
miliseconds=miliseconds+1;
if(miliseconds==100)
{
miliseconds=0;
seconds=seconds+1;
}
if(seconds==60)
{
seconds=0;
minutes=minutes+1;
}
repaint();
}

public static void main(String[]args)
{
JavaSimpleTimer myTest=new JavaSimpleTimer();
}
}


*******************************************************************
JUST COMPILE AND EXECUTE IT
*******************************************************************
Related Posts Plugin for WordPress, Blogger...

I Also Can Create T-Shirt Logo For You