2

I have been working on Java Swing for a while. I paint something(draw some basic shapes like circle,rectangle etc) on a JDesktopPane and once I resize the frame window that contains jDesktopPane or drag some other window over this frame, then the drawn shapes disappear. I use an object of the BufferedImage class so as to save the image. So Is there any way of preventing the shapes getting disappeared or repaint it when they disappear?

jzd
  • 23,473
  • 9
  • 54
  • 76
Goku
  • 104
  • 1
  • 8
  • What method are you doing the painting in? – lins314159 May 19 '11 at 23:01
  • I actually pass the Graphics object and paint using the object when a mouse button is clicked. So I have placed my g.drawLine() or the other methods in formMouseClicked method.. – Goku May 19 '11 at 23:37
  • and that is wrong since as you're finding out, the Graphics object obtained is not durable does not persist when used this way. Better to have your mouseClicked method change a class field and call repaint(). Then the paintComponent method can use the updated field to decide what to paint. – Hovercraft Full Of Eels May 20 '11 at 01:50

2 Answers2

3

You need to make sure you are saving what you paint and repainting it each time in the paintComponent() method. This method is called automatically whenever a repaint is needed (for example: because of a resize).

jzd
  • 23,473
  • 9
  • 54
  • 76
2

I can only provide a guess since you've decided not to post the necessary code, but my suggestions are:

  • Don't get your Graphics object by calling getGraphics on a component. Instead,
  • Be sure to do your drawing in a class that subclasses a JComponent or one of its children (such as a JPanel).
  • draw your BufferedImage in the JComponent's paintComponent method immediately after calling super.paintComponent() in the same method. Use the Graphics object that is provided by the JVM and passed into the method's parameter.
  • To be sure that your paintComponent method's signature is correct, place an @Override annotation immediately before it. Otherwise if it is not correct, the JVM will probably not call it when you expect it to.
  • But also, please when asking a question here, try to give us enough information so we don't have to guess. Since your problem is graphics related, it would make sense to post your graphics-related code, right?
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373