Timer Applicaiton

<< Button Application | Applications | Trivia Game >>

TimerExample

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class TimerExample extends JPanel implements KeyListener, ActionListener
{
	public static int WIDTH=800;
	public static int HEIGHT=600;
	private Font titleFont, regularFont;
	private int x;
	private Timer timer1, timer2;


	public TimerExample() 
	{

		//initialize variables here...
		titleFont = new Font("Roman", Font.BOLD, 18);
		regularFont = new Font("Helvetica", Font.PLAIN, 12);
		x=0;
		timer1 = new Timer(100, this); //1000=1 seconds
		timer2 = new Timer(2000, this); //1000=1 seconds
		timer1.start();

	}
	public static void main(String[] args) {
		TimerExample app= new TimerExample();
		JFrame window = new JFrame("Timer Example");
		window.setSize(WIDTH, HEIGHT);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().add(app);
		window.addKeyListener(app);
		//window.pack();
		window.setVisible(true);

	}
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, getWidth(),getHeight());
		g.setColor(Color.BLUE);
		g.setFont(titleFont);
		g.drawString("Timer Example", 20, 20);
		g.setColor(Color.BLACK);
		g.setFont(regularFont);
		g.drawString("x = "+x, 20, 40);
		g.fillOval(x, 200, 10, 10);

	}
	// update is a workaround to cure Windows screen flicker problem
	public void update(Graphics g){
		paint(g);
	}

	// These 3 methods need to be declares to implement the KeyListener Interface
	@Override
	public void keyTyped(KeyEvent e) {}

	@Override
	public void keyPressed(KeyEvent e) {}

	@Override
	public void keyReleased(KeyEvent e) {}
	@Override
	public void actionPerformed(ActionEvent e) {

	     if (e.getSource()==timer1){
	    	 x=(x+1)%WIDTH;
	     }
	     repaint();
	}

}