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??
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??
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.
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);
}
}
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.