Hey there,
I am building a small database app where I allow users to input and retrieve information in and out of database.

As part of my application I have this table courses and a java file Course.java that models a Course object. My Course objects have field variables courseID, courseName and so on.

As part of my app, I have to retrieve all rows from my course table and I put courseName of every object built out of the rows in a ComboBox.

After this, I have to write to another table and put courseID in there, but ComboBox's selected item is a courseName, not a courseID. Now, I know I can do a "SELECT courseID FROM courses WHERE coursName = " + ComboBox.getSelectedItem(), but that seems messy since two courseIDs may be returned by that SELECT statement.

Would anyone tell me please how to do this?

thank you in advance.

could you please post your source here to elaborate as how can two courses have the same id? also the source of your database will help

well, think of a course as not defined by a courseID and courseName only. In my database, two courses may have the same name, but different course books.

or, in a more general sense, think of a table that stores people's names. two people have the same name, but a different ID.

thanks for trying to help though.

let me rephrase my question.

I want to pass onto my JComboBox an array of Course objects, but I want it to display my Course objects' coursName field. How do I go about it, anyone?

You can populate a JComboBox with any kind of Objects, and it will use the objects' toString() method to display the object, but when you query the selected item you will get the original object.
If you don't want to have your toString() method just returning the name, then use a ListCellRenderer on your JComboBox to format the objects the way you want

Hey JamesCherrill,
thank you once again for helping me. I tried both ways and I found using ListCellRenderer a little more difficult to use. The problem is that getListCellRendererComponent method returns a component, which forces me to return JLabels, which then don't look nice in my ComboBox.

thank you very much. kind regards.

Yes, a custom renderer is harder, and needs a lot more code, but it does give you complete control. It's a trade-off.
Anyway, glad you;re OK.

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.