簡體   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