当我从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上都只显示"图片未找到"。
new ImageIcon("C:\\Users\\xerof_000\\Pictures\\tmspictures\\" + name + ".jpg");
即可立即工作呢?(尽管这不太可维护,因为它只能在您的计算机上运行,我同意)。 - Guillaume Poletjava -cp .;foo.jar
(Windows)/java -cp .:foo.jar
(Unix / Linux / MacOS)运行程序,则可以使用getResource("/bar.png")
访问该文件。您还可以直接将文件嵌入到jar中。 - Guillaume Polet