I’m working on a project that requires GUI, but I have no experience with GUI, so everything I have been doing is guesswork in a sense.
I have a created an arraylist of objects that I have put into a JList, and now I am trying to change the text in a label based on what the user chooses. I get an error that says “Cannot refer to a non-final variable library inside an inner class defined in a different method”
The arraylist I am using is populated with objects that I can call strings from
How do I get this to work?
JList list = new JList(bookNames.toArray());
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
typeLabel.setText(library.get(list.getSelectedIndex()).getType());
}
});
You cannot access the typeLabel variable inside your new ListSelectionListener(){…}.
A Quick fix would be to declare the typeLabel as final.
This means that you cannot reassign another value to typeLabel but that’s probably fine.
edit:
Also, list must be declared final.