JComboBox + JPA

I am currently stuck on a Java issue considering the java persistance API and JComboBox.

The issue is as follows:

I have a JDialog, whom I use to add something to the database.

In the view:

cbGenre = new JComboBox();
cbPublisher = new JComboBox();

What I want, is in these 2 combo boxes, to be loaded the values out of a List or ArrayList. Standard, from what I found out, was a combobox only accepting a String array. I also found one example that uses ArrayList, whom I can work with.

Now the main question is:

I have 2 tables(only columns that matter will be listed):

games
id pk int
genre int

genre
id pk int
name varchar

They are connected via JPA in a M:1 relationship

so one game can only have one genre
one genre can have one or more games

How will I go about to add the retrieved genre names in the appropriate combobox, and when I press the save button, retrieve both the id of the name in the combobox and the id of that name?

Is this possible via an ArrayList, or does a JCombobox not allow value pairs? The reason I want this, is when I save a game to the database, I need to have the selected genre id and add it to the database, and obviously, the user should not see an id, but rather Action, or RPG and what not.

Sorry if my question is a bit unclear. If it is, please do tell me so I can try to explain it better.

English is not my native tongue, whom you have probably noticed by now 🙂

Thanks for reading and I hope to find a solution soon. In the meantime ill browse trough google some more

Answer

A combo box accepts any kind of objects. To display their value, it uses tht toString() method of the objects. So, you may have this code :

@Entity
public class Genre {
    // fields and methods

    @Override 
    public String toString() {
        return this.name;
    }
}

// in your GUI
List<Genre> genres = findAllGenresSortedByName();
this.cbGenre = new JComboBox(genres.toArray());
// ...
Genre selectedGenre = (Genre) this.cbGenre.getSelectedItem();

If Genre already have a toString method that you don’t want to change, you may wrap a genre inside a dedicated class used for the GUI, and use a combo box of GenreWrappers rather than a combo box of Genres

public class GenreWrapper {
    private Genre genre;

    public GenreWrapper(Genre genre) {
        this.genre = genre;
    }

    @Override
    public String toString() {
        return this.genre.getName();
    }

    public Genre getGenre() {
        return this.genre;
    }
}

You should definitely read the Swing tutorial, and read the javadoc of the swing components you’re using.

Leave a Reply

Your email address will not be published. Required fields are marked *