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

时间:2015-07-25 18:51:36

标签: java swing event-handling jtextfield jcombobox

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

我想更改第一个组合框的值,并希望在更改时自动更新下一个组合框,同样在更改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);

请通过编辑代码来提供帮助,这样可以有一个清晰的想法......谢谢

1 个答案:

答案 0 :(得分:1)

而不是添加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); } }); 。然后您就可以像这样使用ComboBox

TextField

添加您可以对其进行扩展,以便在actionPerformed方法中更改ActionListener #! /bin/bash for i in $(seq -f "%06g" 0 1000) do echo "set term pdf enhance color" > script.plg echo "set output 'demo.pdf'" >> script.plg echo "plot 'test_$i.gnu' with lines" >> script.plg echo "set output" gnuplot < script.plg evince demo.pdf & sleep 0.3 done; 的值。

我认为这就是你的意思,虽然我对你ctrl+c的意图可能有误。