JAVA:[Swing]-JComboBox

问题描述 投票:1回答:1

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

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);

        }
    });

假设选择的对象是Paul,而我在John之后选择。因此,此处会触发actionPerfomed,并且comboBox.getSelectedItem();将返回我们John。我的问题有什么办法可以在之前拦截Paul

java swing jcombobox
1个回答
1
投票

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

comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    String selected = (String) event.getItem();
                    // add your logic
                }
            }
        });
© www.soinside.com 2019 - 2024. All rights reserved.