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

我正在做一个砖头游戏。 我希望每0.1秒后屏幕变得清晰,这样我就可以在框架屏幕上重绘每个东西。

有没有办法直接清除框架屏幕没有任何事件发生?

你应该覆盖

public void paint(Graphics g) 

并在那里做你所有的绘画。

然后你启动一个调用的计时器

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

做彼得建议但覆盖paintComponent而不是paint 。

我也怀疑你会发现它会闪烁得非常糟糕(不断重绘整个屏幕)。 你可能想找到一个更好的方法来做到这一点……不幸的是,这不是我所知道的太多的领域。 这是一个简单的弹跳球演示,可能有所帮助 。

如果你想要每X毫秒发生一些事情,你可以使用一个带有ActionListener的javax.swing.Timer 。 至于实际的清算动作,首先想到的是Graphics.clearRect(),但我怀疑可能有更好的方法。