0

我正在尝试在我的面板中绘制矩形。下面是我的图形类:

class MyComponent extends JComponent {
    public void paint(Graphics g) {        
        g.fillRect(30, 30, 100, 100);         
    }   
 }

我有矩形按钮,我在其中添加了这个动作监听器

rect.addActionListener(new ButtonListener());

我的动作实现是:

private class ButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==rect)
        {               
            p1.add(new MyComponent()); 
            p1.repaint();           
        }
    }   
}

但是当我单击矩形按钮时,什么也没有发生。

4

1 回答 1

3

revalidate需要先调用repaint

panel.revalidate();
panel.repaint(); 

通常paintComponent被覆盖而不是paint在 Swing 中super.paintComponent被调用以更新子组件

于 2014-11-22T02:29:48.917 回答