简体   繁体   English

调用返回null的getGraphics()的替代方法

[英]Any alternative to calling getGraphics() which is returning null

Frequently when I call getGraphics() it returns null, even if I set the xxx.getGraphics(); 当我调用getGraphics()时,它经常返回null,即使我设置了xxx.getGraphics(); xxx to be visible (as a Google search shows...) xxx可见(谷歌搜索显示......)

But this doesn't work, and this frustrates me as it is easy and simple to do in C-Sharp. 但是这不起作用,这让我感到沮丧,因为在C-Sharp中这很简单易行。

Does anyone know of a better way of doing this instead of using getGraphics()?? 有没有人知道更好的方法,而不是使用getGraphics()?

Don't use getGraphics(). 不要使用getGraphics()。 Any painting you do will be temporary and will be lost the next time Swing determines a component needs to be repainted. 你做的任何绘画都是临时的,并且在下次Swing确定需要重新绘制一个组件时会丢失。

Instead override the paintComponent() method of a JComponent or JPanel to do your custom painting. 而是覆盖JComponent或JPanel的paintComponent()方法来进行自定义绘制。 See Custom Painting for more details and examples. 有关详细信息和示例,请参见自定义绘画

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). 您通常不希望在Java Swing组件上使用getGraphics,因为如果组件尚未呈现,则它将为null,即使组件已呈现且返回的Graphics对象不为null,它通常也是如果组件被重新绘制(一个不受控制的过程),则短期对象将无法正常工作。

A better alternative is to draw in a JComponent's paintComponent method and using the Graphics object passed into this method as its parameter. 更好的选择是绘制JComponent的paintComponent方法并使用传递给此方法的Graphics对象作为其参数。 If you need to draw something that is to be a background image, also look into drawing on a BufferedImage. 如果您需要绘制一些背景图像,也可以查看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. 当你这样做时,在这里你在图像上调用getGraphics() createGraphics()如果你需要Graphics2D对象, 调用getGraphics() ),这里返回的对象将是稳定的。 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. 您仍然需要通过在paintComponent的Graphics参数上调用Graphics#drawImage(....)以某种方式显示此图像,可以是JLabel显示的ImageIcon,也可以是JComponent的paintComponent方法中显示的Image。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM