Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

removing drawn objects

843806Oct 7 2007 — edited Oct 7 2007
Hi there,

How do you remove drawn objects on a JPanel? Note my example project below which draws a rectangle on a JPanel named WhiteBoard. I include a button that, when pressed, is supposed to remove the rectangle from the WhiteBoard by calling removeAll() and then repainting. I tried calling both repaint() and revalidate(), but neither seemed to show the removal of the rectangle. This approach isn't working. How do we remove drawn objects like this from the JPanel?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class DrawRemove extends JFrame
{
  final WhiteBoard whiteboard = new WhiteBoard();

  public static void main(String[] args)
  {
     DrawRemove dr = new DrawRemove();
     dr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     dr.init();
  }

  public void init()
  {
    setSize(300,300);
    Container container = getContentPane();
    container.setLayout(new BorderLayout());
    JPanel buttonPanel = new JPanel();
    
    JButton remove = new JButton("Remove");
    remove.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
              System.out.println("Remove");
              whiteboard.removeAll();
              whiteboard.repaint();
              //whiteboard.revalidate();
            }
         });

    buttonPanel.add(remove);

    container.add(buttonPanel, BorderLayout.NORTH);
    container.add(whiteboard, BorderLayout.CENTER);

    setVisible(true);
  }

  class WhiteBoard extends JPanel
  {
    public void paintComponent(Graphics g)
    {
       super.paintComponent(g);
       g.setColor(Color.black);
       g.drawRect(5,40,90,55);  
    }
  }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 4 2007
Added on Oct 7 2007
1 comment
507 views