繁体   English   中英

在Graphics2D上调用drawRect方法是否会触发paintComponent方法?

[英]Does invoking the drawRect method on a Graphics2D trigger the paintComponent method?

我正在试图找出我的程序的行为,这是我最好的理论,为什么它做它做的事情。 我希望这会使用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 ,导致自己被无限地称为ad 这不是必需的,因为您已经从Timer调用repaint

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM