javaswingjframejbuttoncustom-painting

Shouldn't use getGraphics() on Jbutton.update, Why?


I always do

Jbutton.setEnabled(false);
Jbutton.update(Jbutton.getGraphics());

when disabling a button, but someone told me that Jbutton.update(Jbutton.getGraphics()); shouldn't be used, or at least not used that way. Why? is it not efficient? Is it incorrect? Should I change my method?


Solution

  • Shouldn't use getGraphics() on Jbutton.update,

    Actually it's wider than that. Programmers should never use getGraphics on any JComponent (or AWT Component) or the same for Swing (and AWT) windows.

    Why?

    Because the painting methods are called by the API, whenever it feels the need to repaint (e.g. restoring a window from minimized, moving another window on top of or away from the window, bringing it to front ..).

    So any call that uses getGraphics is 'transient'.

    [ The correct way to do custom painting is mentioned in Holger's comment, but that wasn't the question. ]