Java 选择新项目时,Swing JComboBox获取上一个项目

Java 选择新项目时,Swing JComboBox获取上一个项目,java,swing,jcombobox,Java,Swing,Jcombobox,我是荡秋千的初学者 我有以下代码: String[] names = new String[]{ "James", "Joshua", "Matt", "John", "Paul" }; JComboBox comboBox = new JComboBox<String>(names); // Create an ActionListener for the JComboBox component. comboBox.addActio

我是荡秋千的初学者 我有以下代码:

String[] names = new String[]{
            "James", "Joshua", "Matt", "John", "Paul" };

    JComboBox comboBox = new JComboBox<String>(names);
    // Create an ActionListener for the JComboBox component.
    comboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            // Get the source of the component, which is our combo
            // box.
            JComboBox comboBox = (JComboBox) event.getSource();

            // Print the selected items and the action command.
            Object selected = comboBox.getSelectedItem();
            System.out.println("Selected Item  = " + selected);

        }
    });
String[]name=新字符串[]{
“雅各”、“约书亚”、“马特”、“约翰”、“保罗”};
JComboBox组合框=新的JComboBox(名称);
//为JComboBox组件创建ActionListener。
comboBox.addActionListener(新ActionListener(){
已执行的公共无效操作(操作事件){
//获取组件的源代码,这是我们的组合
//盒子。
JComboBox组合框=(JComboBox)事件。getSource();
//打印所选项目和操作命令。
所选对象=comboBox.getSelectedItem();
System.out.println(“所选项目=”+所选项目);
}
});

假设选择的对象是保罗,我在约翰之后选择。因此这里触发actionPerfomed,并触发
组合框.getSelectedItem()
将返回我们
John
。我的问题是,以前有没有办法拦截保罗

使用
addItemListener
检查是否选择了任何项目

comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    String selected = (String) event.getItem();
                    // add your logic
                }
            }
        });

资源:

使用
addItemListener
检查是否选择了任何项目

comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    String selected = (String) event.getItem();
                    // add your logic
                }
            }
        });

参考资料:

好吧,你可以使用
项目监听器,它从内存中告诉你“从”和“到”“事件,或者您可以保留对上一个选定值的引用:/以及我如何实现它?好吧,您可以从开始,我认为有一些示例。您可以使用
项目侦听器
,从内存中,它将告诉您“从”和“到”“事件,或者您可以保留对上一个选定值的引用:/以及我如何实现它?好吧,您可以从开始,我认为有一些示例。请注意,这可能会被调用两次,一次用于取消选择,一次用于选择-因此,您可能希望在决定应该做什么之前检查类型。。。既然这是OP提出的基本问题,你可以考虑演示一下。我认为OP需要上一个选中的项目,因此您应该使用
ItemEvent。取消选中
,否则您可以像示例中那样使用ActionLIstener,因为它提供了当前选择。请注意,这可能会被调用两次,一次用于取消选择,一次用于选择-因此,您可能希望在决定应该做什么之前检查类型。。。既然这是OP提出的基本问题,你可以考虑演示一下。我认为OP需要上一个选中的项目,因此您应该使用
ItemEvent。取消选中
,否则您可以像示例中一样使用ActionLIstener,因为这会提供当前选择。