调用返回null的getGraphics()的任何替代方法 [英] Any alternative to calling getGraphics() which is returning null

查看:117
本文介绍了调用返回null的getGraphics()的任何替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我调用getGraphics()时,它经常返回null,即使我设置了xxx.getGraphics(); xxx是可见的(正如Google搜索显示的那样......)

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

但是这不起作用,这让我感到沮丧,因为它在C中很简单易行-Sharp。

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

有没有人知道更好的方法,而不是使用getGraphics()??

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

推荐答案

您通常不希望在Java Swing组件上使用getGraphics,因为如果组件尚未呈现,那么它将为null,即使组件已经渲染并且图形也是如此返回的对象不是null,它通常是一个短暂的对象,如果组件被重新绘制(一个不受控制的进程),它将无法正常工作。

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).

更好的选择是绘制JComponent的paintComponent方法并使用传递给此方法的Graphics对象作为其参数。如果你需要绘制一些背景图像,也可以看一下BufferedImage上的绘图。当你这样做时, 在图像上调用 getGraphics()(或 createGraphics()如果你需要一个Graphics2D对象),这里返回的对象将是稳定的。你仍然需要以某种方式显示这个图像,或者作为JLabel显示的ImageIcon,或者作为JComponent的paintComponent方法中显示的Image,通过调用 Graphics#drawImage(....)

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.

这篇关于调用返回null的getGraphics()的任何替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆