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);
}
}
}