2011-05-25 63 views
1

努力學習java中windows編程,要顯示的圖像的frame.here的問題代碼:圖像中的Java框架不顯示

public static void main(String[] args) throws IOException { 
     JFrame frame = new JFrame("hello world"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(200,200); 
     Graphics graph = frame.getGraphics(); 

     BufferedImage image = ImageIO.read(new File("data/image.jpg")); 
     graph.drawImage(image, 0,0,frame); 
     frame.pack(); 
     frame.setVisible(true); 

    } 

我已經看到了一些成功的例子繼承Component類和調用paint方法中的Graphics.DrawImage方法。爲什麼你必須這樣做,難道你不能只抓取與框架相關的圖形對象,並直接繪製圖像?

回答

4

你不能這樣做,因爲那不是Swing繪畫的作品。首先,繪畫必須發生在EDT上,而實現這一點的首選方法是覆蓋paintComponent(..)方法。但是,如果您使用full screen mode,則可以用您想象的方式進行直接繪畫。

+0

這是正確的,正確的方法來做到這一點,另一個註釋是函數frame.getGraphics(),直到幀被設置爲可見時才返回任何東西。 – 2011-05-25 14:57:59

+0

@Decad哦,從來沒有試圖繪製任何地方,但在'paintComponent(..)'我得到一個'圖形'實例來玩。但很高興知道! – Waldheinz 2011-05-25 15:03:30

+0

paintComponent()是正確的方法,我只是在他的代碼中指出了一些東西。 – 2011-05-25 15:06:13

3

無需自定義繪畫來顯示圖像。見How to Use Icons

本教程還有一個關於「自定義繪畫」的部分。