简体   繁体   中英

JComboBox and JList

I having trouble of what to put in the actionPerformed for the Combo Box . My problem is when I select an Item from the Combo Box it will show a List .

From my code, the cmbCollege has a list of Colleges {"Business", "Computer", "Engineer"}. Selecting an item in the cmbCollege will have a List of Department . For example, when I select "Computer" from the cmbCollege it will show a List, lstDepartment , containing strComputer[] = {"CS", "IT"} and when I selected the other ones it show the corresponding Department like "Business" to strBusiness and "Engineer" to strEngineer .

Here is my code:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class OOP_College extends JFrame implements ActionListener, ListSelectionListener
{
    String strCollege[] = {"Business","Computer", "Engineer"};
    String strBusiness[] = {"Management", "Marketing"};
    String strComputer[] = {"IT", "CS"};
    String strEngineer[] = {"Mechanical", "Electrical", "Electronics"};

    JPanel pnlCollege, pnlDepartment, pnlFaculty;
    JLabel lblCollege, lblChoice, lblDepartment, lblFaculty;
    JComboBox cmbCollege;
    JList lstDepartment;
    JButton btnAdd, btnShow;
    JTextField tfFaculty;
    JTextArea taFaculty;
    GridBagConstraints gbcDepartment = new GridBagConstraints();

    public OOP_College() 
    {
        // TODO Auto-generated constructor stub
        pnlCollege = new JPanel(new FlowLayout());
        lblCollege = new JLabel("Collge: ");
        cmbCollege = new JComboBox(strCollege);
        lblChoice = new JLabel(" - Choice");
        pnlCollege.add(lblCollege);
        pnlCollege.add(cmbCollege);
        pnlCollege.add(lblChoice);

        cmbCollege.setSelectedItem(0);
        cmbCollege.addActionListener(this);

        add(pnlCollege, BorderLayout.NORTH);

        pnlDepartment = new JPanel(new GridBagLayout());
        lblDepartment = new JLabel("Department:");
        lstDepartment= new JList();

        gbcDepartment.gridx = 0;
        gbcDepartment.gridy = 0;
        pnlDepartment.add(lblDepartment, gbcDepartment);

        gbcDepartment.gridx = 1;
        gbcDepartment.gridy = 1;
        pnlDepartment.add(lstDepartment, gbcDepartment);

        add(pnlDepartment, BorderLayout.CENTER);

        pnlFaculty = new JPanel(new FlowLayout());
        lblFaculty = new JLabel("Faculty Name:");
        tfFaculty = new JTextField(20);
        btnAdd = new JButton("ADD");
        btnShow = new JButton("SHOW");
        taFaculty = new JTextArea(10,20);
        taFaculty.setEnabled(false);
        btnAdd.addActionListener(this);
        btnShow.addActionListener(this);
        pnlFaculty.add(lblFaculty);
        pnlFaculty.add(tfFaculty);
        pnlFaculty.add(btnAdd);
        pnlFaculty.add(btnShow);
        pnlFaculty.add(taFaculty);

        add(pnlFaculty, BorderLayout.SOUTH);
    }

    public static void main(String[] args) 
    {
        OOP_College oop = new OOP_College();
        oop.setSize(500,350);
        oop.setVisible(true);
        oop.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }   

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        // TODO Auto-generated method stub
        if(e.getSource() == cmbCollege)
        {
            JComboBox cb = (JComboBox) e.getSource();
            String strSelected = (String) cb.getSelectedItem();
            switch (strSelected)
            {
            }
        }
        else if(e.getSource() == btnAdd)
        {
            taFaculty.setText(taFaculty.getText() + tfFaculty.getText() + "\n");
        }
        else if (e.getSource() == btnShow)
        {
        }

    }

    @Override
    public void valueChanged(ListSelectionEvent e) 
    {
        // TODO Auto-generated method stub

    }
}

You can add ItemsinList Using DefaultListModel here is doc click here DefaultListModel

example :

DefaultListModel listModel = new DefaultListModel();
listModel.addElement("Jane Doe");
listModel.addElement("John Smith");
listModel.addElement("Kathy Green");

and set the DefaultListModel to JList .

 JList list = new JList(listModel);

and you can write your logic in onclicklistener of ComboBox .

switch (strSelected) {
        case "Computer":
            for (int i = 0; i < strComputer.length; i++) {
                model.addElement(strComputer[i]);
            }
            break;
        case "Business":
            for (int i = 0; i < strBusiness.length; i++) {
                model.addElement(strBusiness[i]);
            }
            break;
        case "Engineer":
            for (int i = 0; i < strEngineer.length; i++) {
                model.addElement(strEngineer[i]);
            }
            break;
     }

Here is Example:

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class s extends JFrame implements ActionListener, ListSelectionListener {
String strCollege[] = {"Business", "Computer", "Engineer"};
String strBusiness[] = {"Management", "Marketing"};
String strComputer[] = {"IT", "CS"};
String strEngineer[] = {"Mechanical", "Electrical", "Electronics"};
DefaultListModel model;


JPanel pnlCollege, pnlDepartment, pnlFaculty;
JLabel lblCollege, lblChoice, lblDepartment, lblFaculty;
JComboBox cmbCollege;
JList lstDepartment;
JButton btnAdd, btnShow;
JTextField tfFaculty;
JTextArea taFaculty;
GridBagConstraints gbcDepartment = new GridBagConstraints();

public s() {
    // TODO Auto-generated constructor stub
    pnlCollege = new JPanel(new FlowLayout());
    lblCollege = new JLabel("Collge: ");
    cmbCollege = new JComboBox(strCollege);
    lblChoice = new JLabel(" - Choice");
    pnlCollege.add(lblCollege);
    pnlCollege.add(cmbCollege);
    pnlCollege.add(lblChoice);

    cmbCollege.setSelectedItem(0);
    cmbCollege.addActionListener(this);

    add(pnlCollege, BorderLayout.NORTH);

    model = new DefaultListModel();

    pnlDepartment = new JPanel(new GridBagLayout());
    lblDepartment = new JLabel("Department:");
    lstDepartment = new JList(model);

    gbcDepartment.gridx = 0;
    gbcDepartment.gridy = 0;
    pnlDepartment.add(lblDepartment, gbcDepartment);

    gbcDepartment.gridx = 1;
    gbcDepartment.gridy = 1;
    pnlDepartment.add(lstDepartment, gbcDepartment);

    add(pnlDepartment, BorderLayout.CENTER);

    pnlFaculty = new JPanel(new FlowLayout());
    lblFaculty = new JLabel("Faculty Name:");
    tfFaculty = new JTextField(20);
    btnAdd = new JButton("ADD");
    btnShow = new JButton("SHOW");
    taFaculty = new JTextArea(10, 20);
    taFaculty.setEnabled(false);
    btnAdd.addActionListener(this);
    btnShow.addActionListener(this);
    pnlFaculty.add(lblFaculty);
    pnlFaculty.add(tfFaculty);
    pnlFaculty.add(btnAdd);
    pnlFaculty.add(btnShow);
    pnlFaculty.add(taFaculty);

    add(pnlFaculty, BorderLayout.SOUTH);
}

public static void main(String[] args) {
    s oop = new s();
    oop.setSize(500, 350);
    oop.setVisible(true);
    oop.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if (e.getSource() == cmbCollege) {
        JComboBox cb = (JComboBox) e.getSource();
        String strSelected = (String) cb.getSelectedItem().toString();
        model.removeAllElements();
        switch (strSelected) {
            case "Computer":
                for (int i = 0; i < strComputer.length; i++) {
                    model.addElement(strComputer[i]);
                }
                break;
            case "Business":
                for (int i = 0; i < strBusiness.length; i++) {
                    model.addElement(strBusiness[i]);
                }
                break;
            case "Engineer":
                for (int i = 0; i < strEngineer.length; i++) {
                    model.addElement(strEngineer[i]);
                }
                break;

        }
    } else if (e.getSource() == btnAdd) {
        taFaculty.setText(taFaculty.getText() + tfFaculty.getText() + "\n");
    } else if (e.getSource() == btnShow) {
    }

 }

@Override
public void valueChanged(ListSelectionEvent e) {
    // TODO Auto-generated method stub

   }
 }

From what I see in your code, I guess you want to populate the lstDepartment with values based on the selected college. In the actionPerformed method, the switch should look like this:

switch (strSelected) {
    case "Business":
        lstDepartment.setListData(strBusiness);
        break;
    case "Computer":
        lstDepartment.setListData(strComputer);
        break;
    case "Engineer":
        lstDepartment.setListData(strEngineer);
        break;
 }

Based on the selected value, the list will be updated with the values from the corresponding array.

I would recommend you to create a Map<String,String[]> where to store the values displayed in comboBox (the maps keys) and the associated departments for it (the arrays). Bellow is how the code should look:

// The map declaration
private final Map<String, String[]> colleges = new HashMap<>();

// Populating the map and the ComboBox
colleges.put("", new String[]{""}); // Empty combo box selection
colleges.put("Business", new String[]{"Management", "Marketing"});
colleges.put("Computer", new String[]{"IT", "CS"});
colleges.put("Engineer", new String[]{"Mechanical", "Electrical", "Electronics"});
cmbCollege = new JComboBox(colleges.keySet().toArray());

// The refactored switch
lstDepartment.setListData(colleges.get(strSelected));

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