Skip to content

Instantly share code, notes, and snippets.

@hkulekci
Created July 26, 2011 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hkulekci/1108140 to your computer and use it in GitHub Desktop.
Save hkulekci/1108140 to your computer and use it in GitHub Desktop.
Java Timer Example
import java.awt.Graphics;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
*
* @author kulekci
*/
public class area extends JPanel{
private Timer animationTimer = null;
private int max_x = 300;
private int max_y = 400;
private final int obj_w = 20;
private final int obj_h = 20;
private char operation_x = '+';
private char operation_y = '+';
private int current_x;
private int current_y;
private final int ANIMATION_DELAY = 10;
public area(int m_x, int m_y){
max_x = m_x;
max_y = m_y;
}
@Override
public void paintComponent( Graphics g ){
super.paintComponent(g);
this.setBackground(Color.red);
g.setColor( Color.red );
if (obj_w + current_x >= max_x){
operation_x = '-';
}
if (current_x == 0){
operation_x = '+';
}
if (obj_h + current_y >= max_y){
operation_y = '-';
}
if (current_y == 0){
operation_y = '+';
}
if (animationTimer == null){
current_x = 0;current_y = 0;
}else{
current_x = ( (operation_x == '+')?( (1 + current_x) ):( (current_x - 1) ) );
current_y = ( (operation_y == '+')?( (1 + current_y) ):( (current_y - 1) ) );
}
g.fillRect(
current_x,
current_y,
obj_w,
obj_h
);
g.setColor(Color.blue);
g.drawString("X:"+current_x + " - Y:"+current_y, 100, 100);
}
public void startAnimation(){
if (animationTimer == null){
current_x = 0;
current_y = 0;
animationTimer = new Timer(ANIMATION_DELAY, new TimerHandler() );
animationTimer.start();
}else{
if (!animationTimer.isRunning()){
animationTimer.restart();
}
}
}
public void animationStop(){
animationTimer.stop();
animationTimer = null;
}
private class TimerHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
repaint();
}
}
}
import javax.swing.JFrame;
/**
*
* @author kulekci
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame("Users Main Form");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
area area_1 = new area();
frame.add(area_1);
frame.setSize(300,400);
frame.setVisible(true);
area_1.startAnimation();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment