刷新JComboBox中的下拉列表项目

时间:2016-04-11 06:59:50

标签: java swing

我需要在使用兴奋剂之前刷新下拉列表项。我选择focusGained事件。但是当我停用/激活表单时,我在actionPerformed中触发了两个打印出来的事件:

***null
***aaa

我没有选择任何下拉选择为什么他们在那里?

focusGained是否适合刷新JComboBox中的项目?什么是更好的地方?

package components;

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

public class ComboBoxDemo extends JPanel
                          implements ActionListener , FocusListener {
    JLabel picture;

    public ComboBoxDemo() {
        super(new BorderLayout());

        JComboBox petList = new JComboBox();
        petList.addItem("1");
        petList.addItem("2");
        petList.addItem("3");
        petList.addActionListener(this);
        petList.addFocusListener(this);


        add(petList, BorderLayout.PAGE_START);
        setBorder(BorderFactory.createEmptyBorder(200,200,200,200));
    }

    /** Listens to the combo box. */
    public void actionPerformed(ActionEvent e) {
        JComboBox cb = (JComboBox)e.getSource();
        String petName = (String)cb.getSelectedItem();

        System.out.println("***"+ petName);

    }


    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("ComboBoxDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new ComboBoxDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing  this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    public void focusGained(FocusEvent fe) {

        JComboBox cb = (JComboBox)fe.getSource();
        cb.removeAllItems();
        cb.addItem("aaa");

    }

    public void focusLost(FocusEvent fe) {
    }
}

0 个答案:

没有答案