如何添加侦听器以便在更改组合框值时

How to add listener so that when a combobox value is changed

我已尝试使用建议的方法,但无法确定如何按照建议在动作侦听器中使用动作侦听器...

我想更改第一个组合框的值并希望下一个组合框在更改时自动更新,类似地,当 combobox_1 更改时文本框也会更改...

    String[] b = a.getCourseCodes();
    final List f = new ArrayList();

    final JComboBox comboBox = new JComboBox(b);
    comboBox.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

            String item = comboBox.getSelectedItem().toString();
         }
    });

    comboBox.setEditable(true);

    comboBox.setBounds(360, 70, 86, 20);
    contentPane.add(comboBox);

    JLabel lblStudentName = new JLabel("Student Name");
    lblStudentName.setBounds(270, 149, 80, 14);
    contentPane.add(lblStudentName);

    String[] v = a.getStudentID(comboBox.getSelectedItem().toString());
    final JComboBox comboBox_1 = new JComboBox(v);
    comboBox_1.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

            String item = comboBox_1.getSelectedItem().toString();
         }
    });

    comboBox_1.setBounds(360, 108, 86, 20);
    contentPane.add(comboBox_1);

    textField_3 = new JTextField();
    String y = a.getStudentName(comboBox_1.getSelectedItem().toString());
    textField_3.setText(y);
    textField_3.setEditable(false);
    textField_3.setBounds(360, 146, 86, 20);
    contentPane.add(textField_3);
    textField_3.setColumns(10);

请帮助编辑代码,以便有一个清晰的思路...谢谢

而不是添加 ItemListener 我会简单地添加一个 ActionListener ,每次更改所选值时都会触发它。然后你就可以像这样使用 comboBox.getSelectedItem():

JComboBox comboBox_1; //you need to declare the comboBox and textField before the ActionListener.
comboBox.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        String[] v = a.getStudentID(comboBox.getSelectedItem().toString());
        comboBox_1.setModel(new DefaultComboBoxModel<String>(v));

        String y = a.getStudentName(comboBox_1.getSelectedItem().toString());
        textField_3.setText(y);
    }
});

添加您可以扩展它以在 actionPerformed 方法中更改 ComboBoxTextField 的值。

我认为这就是你的意思,尽管我可能对你的意图有误ActionListener