Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

removing drawn objects  RSS feed

 
Alan Shiers
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
removeAll removes components that have been added to the container; since there are none, the method does nothing.

invalidate causes all components to be layout anew; again, there are no components here.

repaint will cause the container to be, well, repainted, which will lead to paintComponent being called. Since that paints the rectangle, nothing changes.

So in order not to draw the rectangle, paintComponent needs to have logic that prevents this from happening. Or, alternatively, have the code handling the button NOT call repaint, but instead have it draw the rectangle in the background color, or simply paint all of the JPanel in the background color.

The latter method may not work well, though, since Swing may decide to call repaint at various times when your code may or may not be expecting it to. The best way is to have paintComponent paint exactly what you want to show.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Make the drawing depend on the state of some member variable(s), then have the event handler change their values:


[ October 07, 2007: Message edited by: Ernest Friedman-Hill ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!