tags:

views:

98

answers:

3

I am making a brick game. I want the screen to get clear after every 0.1 second so that i can redraw every thing on the frame screen.

Is there any way to directly clear the frame screen without any event occurence??

A: 

If you want something to happen every X milliseconds, you can use a javax.swing.Timer which takes an ActionListener. As for the actual clearing action, the first thing that comes to mind is Graphics.clearRect() but I suspect there may be a better way.

MatrixFrog
+1  A: 

You should override

public void paint(Graphics g)

and do all your drawing in there.

Then you start a timer, which calls

repaint();

Here is a basic example:

public class MainFrame extends JFrame {

    int x = -1;
    int inc;

    public MainFrame() {
        Timer timer = new Timer(10, new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                MainFrame.this.repaint();
            }
        });
        timer.start();
    }

    public void paint(Graphics g) {
        // don't call super.paint(g), we do all the painting

        if(x > getWidth()) inc = -5;
        if(x < 0) inc = 5;

        x += inc;

        // here we clear everything
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, getWidth(), getHeight());

        g.setColor(Color.BLUE);
        g.drawLine(x, 0, getWidth()-x, getHeight());
    }

    public static void main(String[] args) {
        MainFrame mainFrame = new MainFrame();
        mainFrame.setSize(800, 600);
        mainFrame.setVisible(true);
    }
}
Peter Lang
I did its not working here.I mean the new rectangle is getting over written on the previous one.resulting in a complete mess. I want my paint mehthod to first clear all the previous drawings and then redraw it..Its not happening here...
Mew 3.2
I don't see how this could happen. Have you tried to run a copy of my example without changing anything to see if that works? Maybe you could post the relevant parts of your code?
Peter Lang
A: 

Do what Peter suggested but override paintComponent instead of paint.

I also suspect that you will find that this will flicker pretty badly (redrawing the whole screen constantly). You might want to find a better way to do that... unfortunately that isn't an area I know too much about. Here is a simple bouncing ball demo that might help.

TofuBeer
Excellent link to the sun earticle! I would override paintComponent if I would like to have the border painted by Swing. Since that's not what I wanted I used paint to increase performance. The flickering you refer to can be avoided by double-buffering (described in the sun article).
Peter Lang