为什么更改后JComboBox上的itemStateChanged被调用两次? [英] Why is itemStateChanged on JComboBox is called twice when changed?

查看:94
本文介绍了为什么更改后JComboBox上的itemStateChanged被调用两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有ItemListener的JComboBox。更改值时,将调用itemStateChanged事件两次。第一个调用,ItemEvent显示所选的原始项目。第二次,它显示用户刚刚选择的项目。这里有一些测试人员代码:

I'm using a JComboBox with an ItemListener on it. When the value is changed, the itemStateChanged event is called twice. The first call, the ItemEvent is showing the original item selected. On the second time, it is showing the item that has been just selected by the user. Here's some tester code:

public Tester(){

    JComboBox box = new JComboBox();
    box.addItem("One");
    box.addItem("Two");
    box.addItem("Three");
    box.addItem("Four");

    box.addItemListener(new ItemListener(){
        public void itemStateChanged(ItemEvent e){
            System.out.println(e.getItem());
        }
    });

    JFrame frame = new JFrame();
    frame.getContentPane().add(box);
    frame.pack();
    frame.setVisible(true);
}

因此当我将组合框从一改为三时控制台显示:

So when I changed the Combo box once from "One" to "Three" the console shows:

One
Three

我可以告诉使用ItemEvent,它是第二项(即用户选择的项目)吗?如果有人可以解释为什么它被调用两次,那也会很好!

Is there a way I can tell using the ItemEvent maybe, that it's the second item (ie. the user selected item)? And if someone can explain why it gets called twice, that would be nice too!

谢谢

推荐答案

看一下这个来源:

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

public class Tester {

    public Tester(){

        JComboBox box = new JComboBox();
        box.addItem("One");
        box.addItem("Two");
        box.addItem("Three");
        box.addItem("Four");

        box.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent e){
                System.out.println(e.getItem() + " " + e.getStateChange() );
            }
        });

        JFrame frame = new JFrame();
        frame.getContentPane().add(box);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String [] args) {
        Tester tester = new Tester();
    }
}

使用getStateChange确定是否选择了某个项目或取消选择

Use the getStateChange to determine if an item is selected or deselected

这篇关于为什么更改后JComboBox上的itemStateChanged被调用两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆