【发布时间】:2013-02-17 09:44:46
【问题描述】:
每当从 JComboBox 中选择项目时,我都会尝试从图像文件夹中将图标设置为 JLabel。 JComboBox 中的项目名称和文件夹中的图像名称相同。因此,每当从 JComboBox 中选择一个项目时,应将具有相同名称的相应图像设置为 JLabel 的图标。我正在尝试做这样的事情。
private void cmb_movieselectPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt){
updateLabel(cmb_moviename.getSelectedItem().toString());
}
protected void updateLabel(String name) {
ImageIcon icon = createImageIcon("C:\\Users\\xerof_000\\Pictures\\tmspictures\\" + name + ".jpg");
if(icon != null){
Image img = icon.getImage();
Image newimg = img.getScaledInstance(lbl_pic.getWidth(), lbl_pic.getHeight(), java.awt.Image.SCALE_SMOOTH);
icon = new ImageIcon(newimg);
lbl_pic.setIcon(icon);
lbl_pic.setText(null);
}
else{
lbl_pic.setText("Image not found");
lbl_pic.setIcon(null);
}
}
protected static ImageIcon createImageIcon(String path) {
URL imgURL;
imgURL = NowShowing.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
return null;
}
}
我认为问题出在“C:\Users\xerof_000\Pictures\tmspictures\”中,我尝试使用“C:/Users/xerof_000/Pictures/tmspictures/”,但即使这样也没有用。无论我做什么,它只会在 JLabel 上显示“找不到图像”。
【问题讨论】:
-
请看看我的这个答案,对于如何add images to your resource folder,这可能会对这个主题有所帮助:-) 最后一个链接肯定会指导你,如果你这样做一切手动操作,无需使用任何 IDE。如果还有什么不清楚的,请询问:-)
-
当
new ImageIcon("C:\\Users\\xerof_000\\Pictures\\tmspictures\\" + name + ".jpg");可以立即工作时,为什么要做这么复杂的事情? (虽然这不太容易维护,因为它只能在您的计算机上运行,我同意)。 -
@GagandeepBali 我是从 NetBeans 做的,所以我检查了 NetBeans 链接。问题是,我还在 .jar 文件运行时将图片添加到图像文件夹中。我不能在运行 .jar 文件时将图像添加到 .jar 文件中的包中吗?那么有没有办法从运行 .jar 文件的文件夹中读取图像?
-
@GuillaumePolet 谢谢你为我工作。但是有没有办法可以从运行 .jar 文件的文件夹中读取图像?
-
@RaedShahid 是的,如果该文件夹在类路径上,或者是类路径上文件夹的子文件夹。假设您有一个文件夹
root包含一个 jarfoo.jar和一个图像bar.png,如果您使用java -cp .;foo.jar(Windows)/java -cp .:foo.jar(Unix/Linux/MacOS) 运行程序,您可以访问该文件与getResource("/bar.png");。也可以直接将文件嵌入jar中
标签: java swing jlabel jcombobox imageicon