我正在做一个积木游戏。我希望每 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()但我怀疑可能有更好的方法。