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()应该清除框架并在该位置绘制矩形,但仍保留先前绘制的矩形。那么,该怎么做呢?请解释你的答案。
发布于 2011-02-05 11:18:42
您是否尝试过在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();
}
});
}
}发布于 2011-02-05 10:52:06
每次你也需要重新绘制背景。在绘制矩形之前添加用于绘制背景的代码。
发布于 2011-02-05 10:54:57
您需要先清除背景。
资源是这样的:
http://java.sun.com/products/jfc/tsc/articles/painting/
https://stackoverflow.com/questions/4904807
复制相似问题