如何在java中清除我的框架屏幕?

2022-01-24 00:00:00 java swing jframe

我正在做一个积木游戏.我希望每 0.1 秒后屏幕变得清晰,以便我可以重绘框架屏幕上的所有内容.

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??

推荐答案

你应该重写

public void paint(Graphics g)

并在那里完成所有的绘图.

and do all your drawing in there.

然后你启动一个计时器,它会调用

Then you start a timer, which calls

repaint();

这是一个基本的例子:

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

相关文章