Synchronize a jCombobox with a MySQL Table

时间秒杀一切 提交于 2019-12-08 02:43:14

问题


I've created a database application with the NetBeans GUI-Designer.

GUI with Comboboxes (Bound to MySQL databasetables user and team):

on Button new -> jDialog - executes a query to store a new user in database:

Problem: Combobox is updated at the programstart but not while running the program.

Question: Is it possible to update the entries in my combobox directly when a new user or team is saved? And how could I Implement this?

Edit: Here is what I do when clicking on the saveButton in the JDialog:

int k=st.executeUpdate(
    "INSERT INTO User (username) " + " VALUES ('"+ name + "')");
//Here I'd like to update the jComboBox1 directly if possible
Outerclass.jComboBox1...; 
JOptionPane.showMessageDialog(null, "User is successfully saved");' 

回答1:


Just update your component's ComboBoxModel when you insert a new user in the database. If this is not helpful, please provide an sscce that exhibits the problem.

Addendum: Given a reference to a JComboBox,

private final JComboBox combo = new JComboBox();

you can update its model, as shown below. This example adds name to the beginning of the list, but SortedComboBoxModel is an appealing alternative.

DefaultComboBoxModel model = (DefaultComboBoxModel) combo.getModel();
model.insertElementAt(name, 0);

Addendum: More simply, use the method available to the combo itself,

combo.insertElementAt(name, 0);



回答2:


I ran into a similar problem: if you enter anything into the database, that is supposed to be reflected in the JComboBox, then you can't change the values of that combo box. It would be great if you could add things to the JComboBox "on the fly" directly, but you have to get that data, create a new ComboBoxModel from it, and then set your JComboBox to that new model.

Here, I use DefaultComboBoxModel, which can either take an array of objects (usually strings) or a vector. If you use vectors to represent your underlying data model, that's a lot easier, since vectors are dynamic data structures.

My code:

Vector<String> s = new Vector<String>();
try {
    // I'm using prepared statements, get the ResultSet however you like
    ResultSet rs = myPreparedStatement.executeQuery(); 
    while ( rs.next() ) {
        // Change "1" to whatever column holds your data
        s.add(rs.getString(1)); 
    }
} catch (SQLException ex) {
    ex.printStackTrace(); // or whatever
}
DefaultComboBoxModel jcbModel = new DefaultComboBoxModel(s);
jcb.setModel(jcbModel);

EDIT: Remember that ResultSet columns are 1-indexed, not 0-indexed! Gets me every time.



来源:https://stackoverflow.com/questions/8267635/synchronize-a-jcombobox-with-a-mysql-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!