Java 在Graphics2D上调用drawRect方法是否会触发paintComponent方法?
我试图弄清楚我的程序的行为,这是我最好的理论,它为什么会这样做。我希望这将使用Java 在Graphics2D上调用drawRect方法是否会触发paintComponent方法?,java,swing,jpanel,repaint,paintcomponent,Java,Swing,Jpanel,Repaint,Paintcomponent,我试图弄清楚我的程序的行为,这是我最好的理论,它为什么会这样做。我希望这将使用rand变量来决定要绘制的形状,但是相反,paintComponent方法似乎在计时器触发之间被多次调用,导致许多形状被绘制,我试图理解原因 代码如下: public class TestPane extends JPanel { private int yPos0; private int yPos1; private int boundary0=750; private Actio
rand
变量来决定要绘制的形状,但是相反,paintComponent
方法似乎在计时器触发之间被多次调用,导致许多形状被绘制,我试图理解原因
代码如下:
public class TestPane extends JPanel {
private int yPos0;
private int yPos1;
private int boundary0=750;
private ActionEvent ae = null;
private Graphics g0 = null;
private int count=1;
public TestPane(Color foreground){
setForeground(foreground);
this.setBackground(Color.BLUE);
Timer timer = new Timer(3000,new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
ae = e;
yPos0 =yPos0+50;
repaint();
}
});
timer.start();
}
@Override
public void paintComponent(Graphics g){
g0 = g;
super.paintComponent(g);
createShape(yPos0);
repaint();
}
public void createShape(int ypos0){
//generate random number between 1 and 3 and assign to rand
int rand = (int)((Math.random()*3)+1);
System.out.println(rand);
if(rand==1){
Graphics2D g2d = (Graphics2D) g0.create();
g2d.setColor(Color.RED);
g2d.drawRect(0, ypos0, 200, 50);
}
if(rand==2){
Graphics2D g2d = (Graphics2D) g0.create();
g2d.setColor(Color.GREEN);
g2d.drawRect(0, ypos0, 150, 50);
g2d.drawRect(50, ypos0+50,50,50);
}
}
}
调用
paintComponent
的次数如此之多的原因是,您在该方法中调用了repaint
,这会导致其自身被无限调用。这是不需要的,因为您已经在从计时器调用重新绘制