aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes add item in jcombobox from database Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "add item in jcombobox from database" Watch "add item in jcombobox from database" New topic
Author

add item in jcombobox from database

Ah Ling
Greenhorn

Joined: Dec 28, 2009
Posts: 12
How do I add items in jcombobox from the database?
I have been trying and trying for hours and yet I still cant figure out.

Any examples to show for me to try out for reference?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19696
    
  20

JComboBox. This page has a nice linked called "How to Use Combo Boxes". The page also includes all methods, one of which is "addItem".

As for the items to put in there, you will need to create a class for your database contents. I can't tell you what this class should look like because it all depends on the data inside it.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Ah Ling
Greenhorn

Joined: Dec 28, 2009
Posts: 12
Hello!

Yes, i know how to add items in the jcombobox and i already have a class for my database.

Can I know if this is correct?

private JComboBox getJComboBoxStudent() {
if (jComboBoxStudent == null) {
jComboBoxStudent = new JComboBox();
jComboBoxStudent.setBounds(new Rectangle(165, 105, 166, 31));

jComboBoxStudent.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {

std.retrieveStudent();
jComboBoxStudent.addItem(std.getStudentName().toString());
}
});
}
return jComboBoxStudent;
}
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19696
    
  20

Please use code tags. That will make your code easier to read.

Now, about your code. As I see it, you create your student combo box when you need it. You set its bounds but you don't add it to any control. Perhaps that is in the calling method. Either way, the setBounds is not encouraged; you should use a proper layout manager which will set the bounds for you.

Anyway, getting back to your code. You add an action listener that will retrieve another student (which one?) which you then add. Is this really what you want? Wouldn't you want to load all students from the database immediately and store those in your combo box? A combo box can store any object; it will use the result of toString() by default to display it but you can override this by using your own ListCellRenderer.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: add item in jcombobox from database