how do i clear my frame screen in java?

痞子三分冷 提交于 2019-12-04 15:24:25

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

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!