gpt4 book ai didi

java - Swing中是否有监听启用/禁用事件的监听器?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:09:55 25 4
gpt4 key购买 nike

是否有我可以添加到 Swing 组合框的监听器,该监听器将在启用或禁用组合框时触发?

我尝试过不同的监听器,例如 componentlistener、itemlistener、propertychangelistener,但都无济于事。我正在使用 JDK 1.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());
}
});
}

}

}

关于java - Swing中是否有监听启用/禁用事件的监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25302612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com