程序添加JComboBox的item也能触发itemStateChanged事件吗
直接看实例:
- package share;
- import java.awt.EventQueue;
- import java.awt.GridBagConstraints;
- import java.awt.GridBagLayout;
- import java.awt.Insets;
- import java.awt.event.ItemEvent;
- import java.awt.event.ItemListener;
- import javax.swing.JButton;
- import javax.swing.JComboBox;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- import javax.swing.border.EmptyBorder;
- import com.string.widget.util.ValueWidget;
- public class TestJComboBox extends JFrame {
- private JPanel contentPane;
- private JComboBox<String> comboBox;
- /**
- * Launch the application.
- */
- public static void main(String[] args) {
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- try {
- TestJComboBox frame = new TestJComboBox();
- frame.setVisible(true);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- }
- /**
- * Create the frame.
- */
- public TestJComboBox() {
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setBounds(100, 100, 450, 300);
- contentPane = new JPanel();
- contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
- setContentPane(contentPane);
- GridBagLayout gbl_contentPane = new GridBagLayout();
- gbl_contentPane.columnWidths = new int[]{0, 0, 0};
- gbl_contentPane.rowHeights = new int[]{0, 0};
- gbl_contentPane.columnWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
- gbl_contentPane.rowWeights = new double[]{0.0, Double.MIN_VALUE};
- contentPane.setLayout(gbl_contentPane);
- comboBox = new JComboBox<String>();
- GridBagConstraints gbc_comboBox = new GridBagConstraints();
- gbc_comboBox.insets = new Insets(0, 0, 0, 5);
- gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
- gbc_comboBox.gridx = 0;
- gbc_comboBox.gridy = 0;
- contentPane.add(comboBox, gbc_comboBox);
- JButton btnAddItem = new JButton("add item");
- GridBagConstraints gbc_btnAddItem = new GridBagConstraints();
- gbc_btnAddItem.gridx = 1;
- gbc_btnAddItem.gridy = 0;
- contentPane.add(btnAddItem, gbc_btnAddItem);
- comboBox.addItemListener(new ItemListener()
- {
- @Override
- public void itemStateChanged(ItemEvent arg0)
- {
- System.out.println("itemStateChanged");
- }
- });
- init222();
- }
- private void init222(){
- comboBox.addItem("a");
- comboBox.addItem("b");
- comboBox.addItem("c");
- }
- }
启动的时候,控制台打印:
itemStateChanged
说明启动之后,执行了itemStateChanged 方法,说明了触发了itemStateChanged 事件.
总结:程序添加addItem 也能触发itemStateChanged 事件
如何把init222 方法放在comboBox.addItemListener 前就不会触发itemStateChanged 事件