简体   繁体   中英

How to add more than one element into ComboBox in Java

I have a table named "kierowca" which has columns named "imie" and "nazwisko". In my application I would like to add to comboBox few items like "imie nazwisko". That is how my comboBox is defined:

public DefaultComboBoxModel kierowcaCbModel = new DefaultComboBoxModel();
JComboBox kierowcaCb = new JComboBox(kierowcaCbModel);

Here is my method which gets "imie" and "nazwisko" from database:

public static String getKierowcaImieNazwisko(int id) {
    String imieNazwisko = "";
    try {
        ResultSet result = stmt.executeQuery("SELECT imie, nazwisko FROM kierowca WHERE id_kierowca="+id+";");
        while(result.next()) {
            imieNazwisko = result.getString("imie") + " " + result.getString("nazwisko");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return imieNazwisko;
}

And here this is how i tried to add few more elements into comboBox:

try {
    ResultSet result = baza.stmt.executeQuery("SELECT id_kierowca FROM kierowca;");
    while(result.next()) {
        view.kierowcaCbModel.addElement(baza.getKierowcaImieNazwisko(result.getInt("id_kierowca")));
    }
} catch(Exception ex) {
    ex.printStackTrace();
}

The problem is that my final comboBox has only first row from the table "kierowca". How to fix that?

EDIT: What more, I can add new item into comoBox manually like view.kierowcaCb.addElement("Hallo"); and it is visible in my final comboBox

since you are modifying the model after it is intialised in the Jframe, you need to repaint the swing.

Try

SwingUtilities.updateComponentTreeUI(frame);

If it still doesn't work then after completing the above step try

frame.invalidate();
frame.validate();
frame.repaint();

if repainting doesnt work then as per documentation:

  • you have to add ComboBoxModel to the JComboBox ,
  • there you can to add / remove / modify the value,

  • events implemented in the API refreshing your view ( JComboBox ) without moreover code lines

  • all updates must be done on Event Dispatch Thread

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM