gpt4 book ai didi

java - 绘制 Graphics2D 绘图后对其进行处理

转载 作者:行者123 更新时间:2023-11-30 04:23:49 25 4
gpt4 key购买 nike

对于我正在开发的游戏,我需要绘制一个越来越小的矩形。我已经弄清楚如何使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com