2014-01-17 95 views
0

我有一個JFrame.I無法將圖像添加到它。我不知道如何給出正確的圖像路徑。無法將圖像添加到JFrame?

String iPath = "RemoteItServer/Mobile.png"; 
       JLayeredPane layeredPane = new JLayeredPane(); 
       layeredPane.setBounds(0, 0, 315, 610); 

       JLabel mobileImageLabel = new JLabel(new ImageIcon(iPath)); 
       mobileImageLabel.setBounds(0, 0, 315, 610); 
       layeredPane.add(mobileImageLabel, Integer.valueOf(0)); 

enter image description here

如果iPath = C://Mobile.png如果我給圖像Shown.But iPath = "RemoteItServer/Mobile.png"iPath = "/RemoteItServer/res/images/Mobile.png"。它沒有顯示圖像。

所以幫我在正確的方向:)

感謝您的幫助......

回答

1

下面的路徑應該工作:

String iPath = "res/images/Mobile.png"; 

編輯:

也許你忘了將窗格添加到框架。

getContentPane().add(layeredPane); 
0

什麼可以幫助很多是將圖像直接放在您正在處理的項目中。這樣你只需要調用「Mobile.png」而不必擔心路徑。

1

路徑可能會非常棘手。如果相對路徑,如由Joschua提供的一個,不能正常工作,則可以拼湊的絕對路徑,像這樣:

字符串工作目錄= System.getProperty(「user.dir來」);
String separator = System.getProperty(「file.separator」);

然後,只需串連到工作目錄的相對路徑:

工作目錄+隔板+ 「RES /圖像/ Mobile.png」;

另一種方式做,這是使用File類,像這樣:

檔案文件=新的文件( 「RES /圖片/ Mobile.png」);
String path = file.getAbsolutePath();

希望這會有所幫助。