Ligerx
Ligerx

Reputation: 11

JLists with Arraylists?

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());
    }
});

Upvotes: 1

Views: 777

Answers (2)

Luka Klepec
Luka Klepec

Reputation: 542

The reference to JList list has to be final.

final JList list = new JList(...)

The final keyword in Java has several meanings. When used with a variable or a field this means that it always references the same object, i.e. the pointer is constant. It does not mean that the object itself is unchangeable (or immutable).

Immutability of objects is achieved in a different way - don't give us any public methods that change the contents of an object. For example Strings and Dates are always immutable regardless of the final keyword.

Another example of final: When used in front of a class it means that a class cannot be subclassed.

Upvotes: 0

alex
alex

Reputation: 1229

You cannot access the typeLabel variable inside your new ListSelectionListener(){...}.

JList list = new JList(bookNames.toArray());

list.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent event) {
        // you cannot access typeLabel here
        typeLabel.setText(library.get(list.getSelectedIndex()).getType());
    }
});

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.

final typeLabel = whatever; // add the final modifier

final JList list = new JList(bookNames.toArray());

list.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent event) {
        typeLabel.setText(library.get(list.getSelectedIndex()).getType());
    }
});

edit: Also, list must be declared final.

Upvotes: 1

Related Questions