2016-08-25 204 views
0

我試圖將圖像「Pic.png」添加到此JLabel「label1」並將其顯示在JFrame「window1」上的JPanel「panel1」上。但是當它運行時它不顯示我的圖像。任何人幫助? (我讀過關於將其添加到源文件或其他內容,但我不確定我在做什麼,因爲我是Java新手,如果沒有源代碼中的圖像,是否無法訪問圖片?)試圖將圖像添加到標籤但不起作用?

public class UIForIshidaQuery { 

    public static void main(String[] args) { 
     System.out.println("Running..."); 

     JFrame window1 = new JFrame(); 
     window1.setVisible(true); 
     window1.setSize(1080, 720); 
     window1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JPanel panel1 = (JPanel) window1.getContentPane(); 
     JLabel label1 = new JLabel(); 
     panel1.setLayout(null); 
     ImageIcon image = new ImageIcon("C:\\Users\\BC03\\Pictures\\Saved Pictures\\Other\\Pic.png"); 
     label1.setIcon(image); 
     label1.setBounds(500, 500, 500, 500); 
     panel1.add(label1); 
    } 
} 
+0

是否有'new File(「C:\\ Users \\ BC03 \\ Pictures \\ Saved Pictures \\ Other \\ Pic.png」)。exists()'return true? – Berger

+0

查看[tag:embedded-resource]標籤中引用的示例[here](http://stackoverflow.com/tags/embedded-resource/info)。 – trashgod

+0

是的,它返回true @Berger – Cutter

回答

2

窗口應作爲最後的呼叫設置可見。請勿使用null佈局。這工作。

import java.net.*; 
import javax.swing.*; 

public class UIForIshidaQuery { 

    public static String url = "http://i.stack.imgur.com/gJmeJ.png"; 

    public static void main(String[] args) throws MalformedURLException { 
     System.out.println("Running..."); 

     JFrame window1 = new JFrame(); 
     window1.setSize(1080, 720); 
     window1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JPanel panel1 = (JPanel) window1.getContentPane(); 
     JLabel label1 = new JLabel(); 
     //panel1.setLayout(null); 
     ImageIcon image = new ImageIcon(new URL(url)); 
     label1.setIcon(image); 
     //label1.setBounds(500, 500, 500, 500); 
     panel1.add(label1); 
     window1.setVisible(true); 
    } 
} 
  1. Java的圖形用戶界面有不同的OS」,屏幕大小,屏幕分辨率等方面的工作在不同的地區使用不同的PLAFs。因此,它們不利於像素的完美佈局。請使用佈局管理器,或combinations of them以及white space的佈局填充和邊框。
+0

謝謝,這個作品! – Cutter

+0

以上信息是正確的,像素完美的佈局很難在Java Swing中實現。因此,爲了檢查現有代碼中的圖像,您可以運行並嘗試最大化/最小化窗口,並且您會看到圖像出現,而您在運行代碼時不會立即出現圖像。 –

1

如果您正在使用的IntelliJ IDEA:

  1. 右鍵點擊你的項目的根目錄,並選擇New>目錄;
  2. 例如調用新的目錄'資源';
  3. 右鍵單擊新建的目錄並選擇標記目錄爲>資源根目錄;
  4. 在目錄中添加您的圖像文件;
  5. 訪問您的文件中正確: CurrentClass.class.getClassLoader().getResource("pic.png").getFile();

的ImageIcon的可以這樣初始化:

File file = new File(CurrentClass.class.getClassLoader().getResource("pic.png").getFile()); 
     BufferedImage image = null; 
     try { 
      image = ImageIO.read(file); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     ImageIcon imageIcon = new ImageIcon(image); 
+0

我沒有使用IntelliJ IDEA。 – Cutter

+0

對不起,我錯過了你添加的netbeans標籤。對於使用IntelliJ IDEA的其他用戶來說仍然是一個很好的參考。 – Thibstars