是否有侦听器侦听Swing中的启用/禁用事件?

时间:2014-08-14 07:44:52

标签: java swing listener

是否有一个可以添加到Swing组合框的监听器,当组合框被启用或禁用时会触发?

我尝试过不同的侦听器,例如componentlistener,itemlistener,propertychangelistener但是徒劳无功。我使用的是JDK 1.6。

1 个答案:

答案 0 :(得分:6)

PropertyChangeListener似乎对我有用......

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class EnabledTest {

    public static void main(String[] args) {
        new EnabledTest();
    }

    public EnabledTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            final JComboBox cb = new JComboBox(new Object[]{"One", "Two", "Three"});
            add(cb, gbc);
            cb.addPropertyChangeListener("enabled", new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    System.out.println("State changed for " + evt.getPropertyName() + " to " + evt.getNewValue());
                }
            });

            JButton btn = new JButton("Switch");
            add(btn, gbc);
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    cb.setEnabled(!cb.isEnabled());
                }
            });
        }

    }

}