Normally, you do not want to use getGraphics for the Java Swing component, since it will be null if the component has not yet been displayed, and even if the component has been rendered, and the returned Graphics object is not null, it will usually be a short-lived object and will not work properly if the component is repainted (a process that is out of your control).
A better alternative is to use the JComponent paintComponent method and use the Graphics object passed to this method as its parameter. If you need to draw something that should be a background image, look at the BufferedImage drawing. When you do this, it will call getGraphics() on the image (or createGraphics() if you need a Graphics2D object), and here the returned object will be stable. You still need to display this image one way or another, as ImageIcon displayed by JLabel, or as an image displayed in the paintComponent method of JComponent, by calling Graphics#drawImage(....) in the paintComponent Graphics parameter.
source share