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()应该清除框架并在该位置绘制矩形,但之前绘制的矩形仍然存在。那么,怎么做呢?请解释一下你的答案。
答案 0 :(得分:14)
您是否尝试在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();
}
});
}
}
答案 1 :(得分:1)
您每次都需要重新绘制背景。在绘制矩形之前添加代码以绘制背景。
答案 2 :(得分:1)