Immediate update to JCombobox in Java

前端 未结 1 628
粉色の甜心
粉色の甜心 2021-01-23 05:19

A person wishes to add a NEW Job to the database. A Combobox list the existing employers already in the database for the new Job to be added against. But if an empl

相关标签:
1条回答
  • 2021-01-23 05:28

    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;
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题