6

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()??

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Alston
  • 2,085
  • 5
  • 30
  • 49
  • 3
    Can you provide us with a context? Perhaps include an [sscce](http://www.sscce.org) demonstrating your problem. – mre Nov 18 '11 at 15:41
  • 1
    If you're trying to customize the way a component is drawn, override `paintComponent` and put your drawing code there. – lhballoti Nov 18 '11 at 15:48

2 Answers2

12

You usually don't want to use getGraphics on a Java Swing component since this will be null if the component has not been rendered yet, and even if the component has been rendered and the Graphics object returned is not null, it will usually be a short-lived object and will not work properly if the component gets repainted (a process that is out of your control).

A better alternative is to draw in a JComponent's paintComponent method and using the Graphics object passed into this method as its parameter. If you need to draw something that is to be a background image, also look into drawing on a BufferedImage. When you do that, here you will call getGraphics() on the image (or createGraphics() if you need a Graphics2D object), and here the object returned will be stable. You'll still need to display this image somehow, either as an ImageIcon displayed by a JLabel or as an Image displayed in a JComponent's paintComponent method, by calling Graphics#drawImage(....) on the paintComponent's Graphics parameter.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
12

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.

camickr
  • 321,443
  • 19
  • 166
  • 288