Java – Any alternative to calling getGraphics() which is returning null

drawdrawingjavaswing

Frequently when I call getGraphics() it returns null, even if I set the xxx.getGraphics(); xxx to be visible (as a Google search shows…)

But this doesn't work, and this frustrates me as it is easy and simple to do in C-Sharp.

Does anyone know of a better way of doing this instead of using getGraphics()??

Best Answer

Don't use getGraphics(). Any painting you do will be temporary and will be lost the next time Swing determines a component needs to be repainted.

Instead override the paintComponent() method of a JComponent or JPanel to do your custom painting. See Custom Painting for more details and examples.

Related Topic