After cicking button its not showing any shape in my panel

40 views Asked by At

I am trying to draw rectangle in my panel. Below it is my graphics class:

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

And I have rectangle button where I add this action Listener

rect.addActionListener(new ButtonListener());

And my action implementations is:

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

But when I click rectangle button nothing happens.

1

There are 1 answers

2
Reimeus On

revalidate needs to be called before repaint

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

Typically paintComponent is overridden instead of paint in Swing with super.paintComponent being called to update child components