gpt4 book ai didi

java - Repaint() 不清除框架

转载 作者:搜寻专家 更新时间:2023-11-01 04:03:37 25 4
gpt4 key购买 nike

public class Graphics2DTest extends JPanel implements ActionListener{
private Timer time = new Timer(5,(ActionListener) this);
int x = 0,y = 0;
public void paintComponent(Graphics g){

Graphics2D gui = (Graphics2D) g;
Rectangle2D rectangle = new Rectangle2D.Double(x,y,100,150);
gui.setPaint(Color.GREEN);
gui.fill(rectangle);
time.start();
}

public void actionPerformed(ActionEvent arg0) {
x++;
y++;
repaint();
}
}

问题是 repaint() 应该清除框架并在该位置绘制矩形,但是之前绘制的矩形仍然存在。那么,怎么做呢?请解释你的答案。

最佳答案

你试过在你的 paintComponent 方法中调用 super.paintComponent(g) 吗?这将清除之前在 JPanel 中绘制的图像:

public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D gui = (Graphics2D) g;
Rectangle2D rectangle = new Rectangle2D.Double(x,y,100,150);
gui.setPaint(Color.GREEN);
gui.fill(rectangle);
//time.start();
}

此外,不要在 paintComponent 方法中启动计时器或执行任何程序逻辑。首先,你无法绝对控制何时或是否调用该方法,其次,该方法必须只关心绘画而不关心其他,并且需要尽可能快。

例如:

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

import javax.swing.*;

public class Graphics2DTest extends JPanel implements ActionListener {
private Timer time = new Timer(5, (ActionListener) this);
int x = 0, y = 0;

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D gui = (Graphics2D) g;
Rectangle2D rectangle = new Rectangle2D.Double(x, y, 100, 150);
gui.setPaint(Color.GREEN);
gui.fill(rectangle);
//time.start();
}

public void actionPerformed(ActionEvent arg0) {
x++;
y++;
repaint();
}

public Graphics2DTest() {
setPreferredSize(new Dimension(700, 500));
time.start();
}

private static void createAndShowUI() {
JFrame frame = new JFrame("Graphics2DTest");
frame.getContentPane().add(new Graphics2DTest());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

关于java - Repaint() 不清除框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4904807/

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