Immediate update to JCombobox in Java

不问归期 提交于 2019-12-02 02:48:43

If I understood you want the new employee that was added to be what is selected in the combobox?

Once you have got the new employees name and added it to combobox, simply call JComboBox#setSelectedItem(Object o) with the name of the new employee.

i.e:

String newEmpName=...;
//code to add new employee goes here
//code to fill combobox with update values goes here
//now we set the selecteditem of the combobox
comboEmployer.setSelectedItem(newEmpName);

UPDATE

As per your comments:

The basics:

1) Get new employee name or whatever identifier matches that of the items in your combobox from your add employee dialog.

2) Than simply call setSelectedItem(name) after the data has been added tocombobox`.

So you might see your Add Employer dialog return a name or have a method to get the name which was added to the database. In your combobox class after dialog is closed, you would refresh the combobox with new entries, get the name added via the add employee dialog and call JComboBox#setSelectedItem(..) with the name we got from Add employer dialog using getters or static variable

i.e:

class SomeClass {

    JFrame f=...;
    JComboBox cb=new ...;

    ...

    public void someMethod() {
       AddEmployerDialog addEmpDialog=new AddEmployerDialog(f);//wont return until exited or new name added

       String nameAdded=addEmpDialog.getRecentName();//get the name that was added

      //clear combobox of all old entries
      DefaultComboBoxModel theModel = (DefaultComboBoxModel)cb.getModel();
      theModel.removeAllElements();

       //refresh combobox with the latest names from db
       fillCombo();

       //now we set the selected item of combobox with the new name that was added
       cb.setSelectedItem(nameAdded);
  }

}

class AddEmployerDialog {

    private JDialog dialog;
    private String empName;//emp name will be assigned when save is pressed or whatever

    public AddEmployerDialog(JFrame frame) {

        dialog=new JDialog(f);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setModal(true);//so that we dont return control until exited or done
        //add components etc
        dialog.pack();
        dialog.setVisible(true);

    }

    public String getRecentName() {
        return empName;
    }

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