Home > Java > javaTutorial > How to Dynamically Populate Dependent JComboBoxes in Java?

How to Dynamically Populate Dependent JComboBoxes in Java?

DDD
Release: 2024-12-20 21:50:10
Original
676 people have browsed it

How to Dynamically Populate Dependent JComboBoxes in Java?

Implementing Dynamic JComboBoxes

To populate data dynamically in JComboBoxes, you can leverage ComboBoxModel and manipulate the model of the dependent JComboBox.

Implementation:

  1. DataModel Creation:
    Create an array of ComboBoxModel objects, each representing a set of data corresponding to a specific JComboBox.
  2. 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"});
    Copy after login
  3. 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()]);
    Copy after login
  4. 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]);
        }
    });
    Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template