我有一个JSplitPane
,理想情况下应该像这样 -
左侧的JList
应具有与右侧JLabel
中显示的图片相对应的名称。
图片可以在项目根目录中的图像文件夹中找到。
无论出于何种原因,选择左侧JList
中的项目不会影响右侧的JLabel
。
public class TextureChooser {
static Main main;
JSplitPane splitPane;
JList textureList;
JLabel texturePic;
String[] textures = {"grass", "stone", "water"};
ImageIcon ic = new ImageIcon("/Users/seanweber/Desktop/Textures/stone.jpg");
public TextureChooser(){
textureList = new JList(textures);
texturePic = new JLabel(ic);
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textureList, texturePic);
}
//Listens to the list
public void valueChanged(ListSelectionEvent e) {
JList list = (JList)e.getSource();
updateLabel(textures[list.getSelectedIndex()]);
}
//Renders the selected image
protected void updateLabel (String name) {
ImageIcon icon = createImageIcon("images/" + name + ".png");
texturePic.setIcon(icon);
if (icon != null) {
texturePic.setText(null);
} else {
texturePic.setText("Image not found");
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
URL imgPath = main.getClass().getResource(path);
if (imgPath != null) {
return new ImageIcon(imgPath);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
images目录的路径如下所示。
- ProjectRoot
- images
- stone
- grass
- water
我最初的假设是我正在错误地检索图像......
大部分代码都是直接从Oracle网站here上的示例中获取的。
答案 0 :(得分:1)
您尚未向ListSelectionListener
...
textureList
textureList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
JList list = (JList) e.getSource();
updateLabel(textures[list.getSelectedIndex()]);
}
});