请教java组合框的事件监听器
publicclassSearchEngineimplementsItemListener{JComboBoxjcb=newJComboBox();Strings="";...
public class SearchEngine implements ItemListener{
JComboBox jcb = new JComboBox();
String s="";
public SearchEngine(){
jcb.addItem("");
jcb.addItem("China");
jcb.addItem("France");
jcb.addItem("Russia");
jcb.addItemListener(this);
//其余代码未写上
}
public void itemStateChanged(ItemEvent e){
s = jcb.getSelectedItem().toString();
System.out.println(s);
}
}
对于这个代码,我希望每当选择了组合框的一项后,屏幕会打印一次该选项,但为什么当我选择了组合框的一项后,屏幕总是打印两遍项目的内容呢?
请各位帮忙指教一下
监听器没有注册两次啊! 展开
JComboBox jcb = new JComboBox();
String s="";
public SearchEngine(){
jcb.addItem("");
jcb.addItem("China");
jcb.addItem("France");
jcb.addItem("Russia");
jcb.addItemListener(this);
//其余代码未写上
}
public void itemStateChanged(ItemEvent e){
s = jcb.getSelectedItem().toString();
System.out.println(s);
}
}
对于这个代码,我希望每当选择了组合框的一项后,屏幕会打印一次该选项,但为什么当我选择了组合框的一项后,屏幕总是打印两遍项目的内容呢?
请各位帮忙指教一下
监听器没有注册两次啊! 展开
1个回答
展开全部
根据文档上说的
Combo boxes also generate item events, which are fired when any of the items' selection state changes. Only one item at a time can be selected in a combo box, so when the user makes a new selection the previously selected item becomes unselected.Thus two item events are fired each time the user selects a different item from the menu.
因此实际上一个是unselected消息,一个是selected消息,所以有两次
lz如果想获取新的选项信息,应该使用ActionListener,而不是ItemListener
以下是文档上的例子
public class ComboBoxDemo ... implements ActionListener {
. . .
petList.addActionListener(this) {
. . .
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
updateLabel(petName);
}
. . .
}
Combo boxes also generate item events, which are fired when any of the items' selection state changes. Only one item at a time can be selected in a combo box, so when the user makes a new selection the previously selected item becomes unselected.Thus two item events are fired each time the user selects a different item from the menu.
因此实际上一个是unselected消息,一个是selected消息,所以有两次
lz如果想获取新的选项信息,应该使用ActionListener,而不是ItemListener
以下是文档上的例子
public class ComboBoxDemo ... implements ActionListener {
. . .
petList.addActionListener(this) {
. . .
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
updateLabel(petName);
}
. . .
}
参考资料: http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询