Implementing Dynamic JComboBoxes
To populate data dynamically in JComboBoxes, you can leverage ComboBoxModel and manipulate the model of the dependent JComboBox.
Implementation:
Model Initialization:
Initialize each model with the corresponding data values, as shown in the example:
models[0] = new DefaultComboBoxModel(new String[]{"A1", "A2"}); models[1] = new DefaultComboBoxModel(new String[]{"B1", "B2", "B3", "B4"}); models[2] = new DefaultComboBoxModel(new String[]{"C1", "C2"});
Initial Model Setting:
Initially, set the model of the dependent JComboBox to the model of the selected option in the main JComboBox:
combo2.setModel(models[combo1.getSelectedIndex()]);
Event Handling:
Add an ActionListener to the main JComboBox to capture changes in selection. When the selection changes, update the model of the dependent JComboBox.
combo1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int i = combo1.getSelectedIndex(); combo2.setModel(models[i]); } });
By following these steps, you can implement dynamic JComboBoxes that populate the dependent JComboBox with relevant data based on the selection made in the main JComboBox.
The above is the detailed content of How to Dynamically Populate Dependent JComboBoxes in Java?. For more information, please follow other related articles on the PHP Chinese website!