Any alternative to calling getGraphics () that returns null

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

But this does not work, and it disappoints me, because it is easy and simple to do in C-Sharp.

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

+6
source share
2 answers

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.

+11
source

Do not use getGraphics (). Any painting you make will be temporary and will be lost the next time Swing determines that the component should be repainted.

Instead, override the JComponent or JPanel paintComponent() method to create your own picture. See Custom painting for more details.

+12
source

Source: https://habr.com/ru/post/901817/