[英]Why this GUI app does not show me the image?
我正在嘗試用JFrame對象編寫一個Java應用程序,該對象必須顯示三個帶有文本和圖像的標簽對象,我的文本“ North”和“ South”在執行時顯示,但是我的圖像卻沒有,即使我放了圖像文件放入src文件夾。
package deitel9;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JFrame;
public class LabelDemo {
public static void main(String[] args)
{
//crate a label with a plain text
JLabel northLabel = new JLabel("North");
//crate an icon from an image so we can put it on a JLabel
ImageIcon labelIcon = new ImageIcon("maldive.jpg");
//crate a label with an Icon instead of text
JLabel centerLabel = new JLabel(labelIcon);
//create another label with an Icon
JLabel southLabel = new JLabel(labelIcon);
//set the label to display text (as well as an icon)
southLabel.setText("South");
//create a frame to hold the labels
JFrame application = new JFrame();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add the labels to the frame; the second argument specifies
//where on the frame to add the label
application.add(northLabel,BorderLayout.NORTH);
application.add(centerLabel,BorderLayout.CENTER);
application.add(southLabel,BorderLayout.SOUTH);
application.setSize(300,300);
application.setVisible(true);
}//end main
}//end class LabelDemo
由於您的圖片存儲在存儲LabelDemo
同一包中,請嘗試執行此操作,
ImageIcon labelIcon = new ImageIcon(LabelDemo.class.getResource("/deitel9/maldive.jpg").getFile());
要么
private String getImage() {
return getClass().getResource("/deitel9/maldive.jpg").getFile();
}
ImageIcon labelIcon = new ImageIcon(new LabelDemo().getImage());
要弄清楚在這種情況下您做錯了什么,您只需致電
File file = new File ("maldive.jpg");
System.out.println(file.getAbsolutePath());
這將打印出它正在尋找文件的絕對路徑,這可能會給您有關您做錯了什么的指示。
當然,如果您知道如何使用調試器,則不需要第二行(技術上甚至不需要第一行,但這有點棘手;))
根據文檔 ,您選擇的ImageIcon
構造函數期望使用文件名或文件路徑,因此圖像需要在文件系統上,而不是在類路徑上。
從指定的文件創建一個ImageIcon。 [...]指定的字符串可以是文件名或文件路徑。
根據您的描述,您的項目布局如下所示
\---src
\---deitel9
LabelDemo.java
maldive.jpg
那么您應該能夠將圖像檢索為位於類路徑上的資源,如下所示:
ImageIcon labelIcon = new ImageIcon(LabelDemo.class.getResource("maldive.jpg"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.