How to use swing timer?

时间:2015-05-24 21:31:41

标签: java swing timer actionlistener

I'm trying to write a program that draws a new square every second. This is my code for my JPannel class. I have two other classes but I beleive they are irrelivant to my question. One has the main method where it creates an object of the other class that contains the JFrame. I just cant figure out how to get the timer to work and how it works.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Drawing extends JPanel  implements ActionListener{
    Drawing(){
        super();
        setBackground(Color.WHITE);
        startTimer();        
    }

    public void startTimer() {
           Timer timer = new Timer(1000, this);
           timer.start();
    }

    public void paintComponent(Graphics g) {
         int width = getWidth();             
         int height = getHeight();         

         super.paintComponent(g);  
         g.setColor(Color.BLUE);

         for(int x = 0; x < 999; x ++) {
         for(int y = 0; y < 999; y ++) {

                 g.drawRect(0,0, x, y);


         }
         }

    }

    public void actionPerformed(ActionEvent e) { 
           repaint();
    }

}

1 个答案:

答案 0 :(得分:3)

Get rid of the for loops in your paintComponent method. Note that painting methods should not change object state. Instead the timer's actionPerformed method gets repeatedly called -- advance your counter or x/y variables there, and then call repaint().

e.g.,

private int x;
private int y;

public void paintComponent(Graphics g) {
     super.paintComponent(g);  
     g.setColor(Color.BLUE);


     // RECT_WIDTH etc are constants
     g.drawRect(x, y, RECT_WIDTH, RECT_HEIGHT);
}


public void actionPerformed(ActionEvent e) { 
    int width = getWidth();             
    int height = getHeight();

    // code here to change the object's state -- here to change
    // location of the rectangle
    x++;
    y++;

    // TODO: check that x and y are not beyond bounds and if so,
    // then re-position them

    repaint();
}