如何创建一个组合框actionListener?

时间:2013-04-16 21:33:46

标签: java jcombobox

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

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

我不知道如何继续,它似乎与用于按钮的那个不同。

3 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分:2)

它应该是相同的只是获取getSelectedValue

框中的值

答案 2 :(得分:1)

试试这个:

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

}
}
}
);