【问题标题】:Does invoking the drawRect method on a Graphics2D trigger the paintComponent method?在 Graphics2D 上调用 drawRect 方法会触发 paintComponent 方法吗?
【发布时间】:2013-03-06 20:10:33
【问题描述】:

我正试图弄清楚我的程序的行为,这是我最好的理论来解释它为什么要这样做。我希望这将使用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);
        }
    }
}

【问题讨论】:

    标签: java swing jpanel repaint paintcomponent


    【解决方案1】:

    paintComponent 被多次调用的原因是您在该方法中调用repaint,导致其自身被调用无限。这不是必需的,因为您已经从您的 Timer 调用 repaint

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多