0

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.

dic19
  • 17,821
  • 6
  • 40
  • 69
Jahidul Islam
  • 29
  • 2
  • 7
  • 2
    Side note: you should not override `paint()` but `paintComponent()` instead. And don't forget to call `super.paintComponent()`. See [A Closer Lookt at the Paint Mechanism](https://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html) – dic19 Nov 22 '14 at 02:30
  • I change it to that Still it is not working – Jahidul Islam Nov 22 '14 at 02:38
  • 1
    Depending on the layout manager of p1, MyComponent may not display because it has no default size. You should also override the getPreferredSize method of MyComponent class to return an appropriate size... – MadProgrammer Nov 22 '14 at 03:08

1 Answers1

3

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

Reimeus
  • 158,255
  • 15
  • 216
  • 276