我如何在 Java 中清除我的框架屏幕?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1957011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do i clear my frame screen in java?
提问by Mahesh Gupta
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.
我正在制作一个砖块游戏。我希望屏幕在每 0.1 秒后变得清晰,以便我可以重绘框架屏幕上的所有内容。
Is there any way to directly clear the frame screen without any event occurence??
有没有什么办法可以直接清帧画面而不发生任何事件??
回答by Peter Lang
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);
}
}
回答by MatrixFrog
If you want something to happen every X milliseconds, you can use a javax.swing.Timerwhich 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.
如果您希望每 X 毫秒发生一些事情,您可以使用带有 ActionListener的javax.swing.Timer。至于实际的清除操作,首先想到的是Graphics.clearRect()但我怀疑可能有更好的方法。
回答by TofuBeer
Do what Peter suggested but override paintComponent instead of paint.
按照 Peter 的建议进行操作,但要覆盖 paintComponent 而不是 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.
我还怀疑您会发现这会非常严重地闪烁(不断重绘整个屏幕)。您可能想找到一种更好的方法来做到这一点……不幸的是,我对这不是一个了解太多的领域。 这是一个简单的弹跳球演示,可能会有所帮助。

