问题
How do I create a combo box action listener? I have the following so far:
myCombo = new JComboBox();
myCombo.addActionListener();
I am not sure how to proceed, it seems that it is different from the one used for the buttons.
回答1:
Try this:
myCombo.addActionListener(new actionListener() {
public void actionPerformed(ActionEvent eventSource) {
JComboBox combo = (JComboBox) myCombo.getSource();
Object selected = combo.getSelectedItem();
if("whatever...") {
}
}
}
);
回答2:
I am not sure where your problem is. However I had this pseudo code which will help you to understand actionlistner on Jcombobox
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();
}
}
回答3:
it should be the same just get the value in the box with getSelectedValue
来源:https://stackoverflow.com/questions/16047518/how-to-create-a-combo-box-actionlistener