对于我正在开发的游戏,我需要绘制一个越来越小的矩形。我已经弄清楚如何使用 Swing 计时器将矩形绘制得更小,如下所示:
timer = new Timer(100, new ActionListener(){
public void actionPerformed(ActionEvent e){
Graphics2D g2d = (Graphics2D) panel.getGraphics();
if(width > 64){
g2d.drawRect(x,y,width,height);
x += 1;
y += 1;
width -= 1;
height -= 1;
}
}
});
timer.start();
我遇到的问题是,它不会删除之前绘制的矩形,因此它看起来不会缩小,而更像是填充。那么,在绘制较小的矩形后,我如何删除先前绘制的矩形?
最佳答案
您可以从以下内容开始:-
更改:
Graphics2D g2d = (Graphics2D) panel.getGraphics();
至:
repaint();
来自 getGraphics()
的 Graphics
实例是暂时的,每当 JVM 认为有必要时,窗口可能会被重新绘制。
重写的方法可能如下所示。
@Override
public void paintComponent(Graphics g){
super.paintComponent(g); // Effectively clears the BG
Graphics2D g2d = (Graphics2D)g;
if(width > 64){
g2d.drawRect(x,y,width,height);
x += 1;
y += 1;
width -= 1;
height -= 1;
}
// Toolkit.getDefaultToolkit().sync();
// g2d.dispose(); NO! Don't dispose of this graphics instance
}
关于java - 绘制 Graphics2D 绘图后对其进行处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374033/