Hello,

So I got the following classes:
Book
BookRegister
GUI
Main

Book contains basic information about what kind of book you want to register. BookRegister contains the linked list for registration. In the GUI, I'm using JList. The thing is, I want to put all my books I register into the JList, and whenever I select one of the books, I want the toString for that book out. Like an information page.
This is a snippet of my code:

private String[] names;
private BookRegister register;

public GUI() {
    names = register.getAllBookNames(); // stores all the names into the array. 

    // methods
}

private class ListListener implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent e) {
        JList list = (JList)e.getSource();
        // I don't know how to select the right book, and get the right toString. Can't find
        // any getXXX which returns toString. 
     }
 }

My problem is that I can't get the toString (with all the information about the book) out. I can't find any getXXX methods which returns a String value. I tried getSelectedValues().toString(); but it didn't work so fell. Found out that it returns the title.

How would I do this?

Thanks.

I tried getSelectedValues().toString(); but it didn't work

What was returned? What was wong wiith it?

Let's say that I've registered a book named Harry Potter. When I click on Harry Potter, I want information out, like
Title: Harry Potter
Pages: 400+
Author: .......
Review: ...........
etc.

With

private class ListListener implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent e) {
            JList list = (JList)e.getSource();
            String t = list.getSelectedValue().toString();
            info.setText(t);
        }
    }

My output is: Harry Potter.

You are printing the value from the JList. If you want more info you could use a Map with the Map's key = the title and Map's value being an object holding all the info for the book. Use the title to get the object from the Map.

Hmm, I've never used Maps before. Is it some easier way to do this?

You don't have to use Strings to populate a JList - you can use any Objects. JList by default will use the objects' toString() method to get the text to display in the list. .
So you can add Book objects to the JList - Then list.getSelectedValue() will return the Book object itself, and you can use that to access whatever info you want to put in the info field.

Maps are one of the easiest ways to do what you want.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.