2016-09-02 80 views
0

所以我試圖在jFrame中顯示一個圖像,在jPanel中。圖像沒有顯示在jPanel

(我想這是你顯示一個JFrame一個JPEG/PNG這樣) 這裏的我在做什麼:

在JFrame的構造函數,我下載的圖像,創建一個ImageIcon,和動態標記jLabel(設置圖標),並將其插入jPanel。

我先前創建JPanel中與NetBeans IDE,其上jPanelImage的initComponents()定義。

如果我用調試程序通過代碼,他下載圖像propery而不會拋出任何異常。

它也正確運行代碼沒有任何問題。

但我的jFrame繼續爲空。 下面的代碼:

public TransmissionFrame() { 
     initComponents(); 

     init(); 
    } 

    private void init() { 

    JLabel label = new JLabel("Java Technology Dive Log"); 
    ImageIcon image = null; 
    try { 
     image = new ImageIcon(ImageIO.read(new URL("http://i.imgur.com/6mbHZRU.png"))); 
    } catch(MalformedURLException mue) { 
     mue.printStackTrace(); 
    } catch(IOException ioe) { 
     ioe.printStackTrace(); 
    } 
    label.setIcon(image); 
    jPanelImage.add(label); 
    jPanelImage.validate(); 
} 

但我的JFrame和JPanel的仍然是空的,爲什麼呢?

+0

你將你的jPanelImage到你的JFrame? – Jacob

+1

是的,我使用NetBeans靜態創建它 – Firecat

+0

您需要將標籤初始化和標籤添加到try catch塊中。我還會在那裏移動JLabel聲明並嘗試JLabel標籤= new JLabel(image);然後將標籤添加到面板。 – Jacob

回答

2

更新,分配佈局到您的JPanel可能是解決

public TransmissionFrame() { 
     initComponents(); 

     init(); 
    } 

private void init() { 
JLabel label = new JLabel("Java Technology Dive Log"); 
ImageIcon image = null; 
try { 
    image = new ImageIcon(ImageIO.read(new URL("http://i.imgur.com/6mbHZRU.png"))); 
} catch(MalformedURLException mue) { 
    mue.printStackTrace(); 
} catch(IOException ioe) { 
    ioe.printStackTrace(); 
} 
label.setIcon(image); 
jPanelImage.setLayout(new FlowLayout()); 
jPanelImage.add(label); 

} 
+0

如果Container使用一個LayoutManager,並且一個LayoutManager應該適當地調整包含'Icon'的JLabel的大小,'setSize的大小將不會執行任何操作。請參閱http://stackoverflow.com/questions/1783793/java-difference-between-the-setpreferredsize-and-setsize-methods-in-compone – copeg

+0

正確的,不更新我的答案 –

0
jPanelImage.setVisibility(true);