0

如何创建组合框动作侦听器?到目前为止,我有以下内容:

myCombo = new JComboBox();
myCombo.addActionListener();

我不确定如何继续,它似乎与用于按钮的不同。

4

3 回答 3

3

我不确定你的问题出在哪里。但是我有这个伪代码,它可以帮助你理解 Jcombobox 上的 actionlistner

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

public class ChangeJlableByJComboBox extends JFrame {

    private static final long serialVersionUID = 1L;

    public ChangeJlableByJComboBox() {
        super("TooltipInSwing");
        setSize(400, 300);
        getContentPane().setLayout(new FlowLayout());
        final JLabel b1;
        final JComboBox jb1 = new JComboBox(new String[] { " ", "one", "two",
                "three" });

        b1 = new JLabel("Default Lable");
        getContentPane().add(b1);
        getContentPane().add(jb1);

        jb1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // setting custom text to JLabel
                if (jb1.getSelectedItem().toString().equals("one"))
                    b1.setText("Lable one ---");
                else if (jb1.getSelectedItem().toString().equals("two"))
                    b1.setText("Lable two ---");
                else if (jb1.getSelectedItem().toString().equals("three"))
                    b1.setText("Lable three ---");
                else
                    b1.setText("----");

                // or Compact version for setting JcomboBox selected item 
                // to JLabel text

                // b1.setText(jb1.getSelectedItem().toString());
                System.out.println(jb1.getSelectedItem().toString());
                // you can also make use of following method
                System.out.println(jb1.getSelectedIndex());
            }
        });

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String args[]) {
        new ChangeJlableByJComboBox();
    }
}
于 2013-04-16T21:46:52.930 回答
2

它应该是相同的,只需使用 getSelectedValue 获取框中的值

于 2013-04-16T21:40:02.443 回答
1

尝试这个:

 myCombo.addActionListener(new actionListener() {
   public void actionPerformed(ActionEvent eventSource) {
   JComboBox combo = (JComboBox) myCombo.getSource();
   Object selected = combo.getSelectedItem();
   if("whatever...") {

}
}
}
);
于 2013-04-16T21:42:36.740 回答