I have a JSplitPane
which ideally should work like this-
A JList
on the left should have names that correspond to a picture displayed in a JLabel
on the right.
The pictures can be found in an images folder located in the project's root directory.
For whatever reason, selecting an item in the JList
on the left bears no effect on the JLabel
on the right.
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;
}
}
The path to the images directory looks like this.
- ProjectRoot
- images
- stone
- grass
- water
My initial assumption is that I'm retrieving the images incorrectly...
Much of the code was taken directly from an example on Oracle's site here.
You haven't added a ListSelectionListener
to the textureList
...
textureList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
JList list = (JList) e.getSource();
updateLabel(textures[list.getSelectedIndex()]);
}
});