2011-09-01 38 views
2

下面是代碼(我延長JFrame的在這個類)(點「大小」是屏幕的大小):Image.getGraphics()返回null

setVisible(true); 
backBuffer = createImage(size.x, size.y); 
backGraphics = backBuffer.getGraphics(); 

我知道,與存在的問題createImage方法,正如它在描述中所說的「如果組件不可顯示,則返回值可能爲null」。然而我設定了可信(真)!這在我的整個計劃中都是一個問題,過去的解決方案很奇怪。然而,這一次,我似乎無法修復它。

它已經定期工作,不工作,也許工作10次運行然後dosnt工作3,並重復循環。

我已經嘗試將createImage鑄造成BufferedImage,由我通過許多谷歌搜索建議,但問題仍然存在。我也試過不擴展jframe,但創建'JFrame jframe = new JFrame()',並使用它來繪製/ etc,但問題仍然存在。

回答

1

這來自here

這些例子創建與屏幕兼容的緩衝圖像:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); 
GraphicsDevice gs = ge.getDefaultScreenDevice(); 
GraphicsConfiguration gc = gs.getDefaultConfiguration(); 

// Create an image that does not support transparency 

bimage = gc.createCompatibleImage(width, height, Transparency.OPAQUE); 

// Create an image that supports transparent pixels 

bimage = gc.createCompatibleImage(width, height, Transparency.BITMASK); 

// Create an image that supports arbitrary levels of transparency 

bimage = gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT); 
+0

太謝謝你了!你不知道你救了我多少個問題......它令人難以置信的煩惱,必須運行5次,直到它工作! – khyperia

+0

不客氣!如果它解決了問題,一定要接受答案,以便問題關閉! –