0

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 4
    You should call `repaint()` instead. But normally, you don’t need to do anything, as `setEnabled(false)` will already trigger the repaint automatically. – Holger Nov 12 '20 at 11:22

1 Answers1

2

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. ]

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433