Java 里怎么监听JComboBox的事件?
publicstaticStringa[]=newString[3];a[0]="x";a[1]="y";a[2]="z";objList=newJComboBox(a)...
public static String a[] = new String [3];
a[0]="x";
a[1]="y";
a[2]="z";
objList = new JComboBox (a);
然后那个actionlistener
public void actionPerformed (ActionEvent e)
{
if (e.getSource () == objList)
{
System.out.println ("catch");
}
}
我要达到的效果是点什么输出什么...
高手们帮忙看看。 展开
a[0]="x";
a[1]="y";
a[2]="z";
objList = new JComboBox (a);
然后那个actionlistener
public void actionPerformed (ActionEvent e)
{
if (e.getSource () == objList)
{
System.out.println ("catch");
}
}
我要达到的效果是点什么输出什么...
高手们帮忙看看。 展开
1个回答
展开全部
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JComboboxTest extends JFrame implements ActionListener {
private JComboBox box;
private String[] a = { "x", "y", "z" };
private JPanel p;
public JComboboxTest() {
box = new JComboBox(a);
box.addActionListener(this);
p = new JPanel();
p.add(box);
this.add(p);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == box) {
int index = box.getSelectedIndex();
switch (index) {
case 0:
//这里可以做别的事情,这样写只是为了告诉你有这个方法。
//box.getSelectedItem() 的返回值是 object
System.out.println(box.getSelectedItem().toString());
break;
case 1:
System.out.println(box.getSelectedItem().toString());
break;
case 2:
System.out.println(box.getSelectedItem().toString());
break;
}
}
}
public static void main(String[] args) {
new JComboboxTest();
}
}
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JComboboxTest extends JFrame implements ActionListener {
private JComboBox box;
private String[] a = { "x", "y", "z" };
private JPanel p;
public JComboboxTest() {
box = new JComboBox(a);
box.addActionListener(this);
p = new JPanel();
p.add(box);
this.add(p);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == box) {
int index = box.getSelectedIndex();
switch (index) {
case 0:
//这里可以做别的事情,这样写只是为了告诉你有这个方法。
//box.getSelectedItem() 的返回值是 object
System.out.println(box.getSelectedItem().toString());
break;
case 1:
System.out.println(box.getSelectedItem().toString());
break;
case 2:
System.out.println(box.getSelectedItem().toString());
break;
}
}
}
public static void main(String[] args) {
new JComboboxTest();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询