我需要创建一些 JSpinner 控件,我可以在其中检测按钮按下,同时使用当前的外观和感觉。我发现我可以很容易地做到这一点,如下所示:
class CustomSpinnerUI extends BasicSpinnerUI {
@Override
protected Component createNextButton() {
// Add custom ActionListener.
}
@Override
protected Component createPreviousButton() {
// Add custom ActionListener.
}
}
问题是这样做我最终会得到一个看起来很讨厌的微调器,它与我的 UI 的其余部分使用不同的外观和感觉。我目前正在使用
Nimbus
但我需要支持不同的 L&F 配置。我想过可能设置某种动态代理,但找不到任何合适的
Spinner
接口(interface)使我能够做到这一点。谁能想到解决问题的方法?我想我要么需要按下按钮
ActionListeners
没有子类 BasicSpinnerUI
,或者想办法让我的CustomSpinnerUI
使用正确的 L&F。编辑:“默认外观”->“当前外观”。
最佳答案
对(公认的)问题“如何访问按钮以挂接自定义 actionListener”的一个肮脏的技术答案是循环通过微调器的子项并将监听器添加到按钮中,由其名称标识:
JSpinner spinner = new JSpinner();
Action action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("button " + ((Component) e.getSource()).getName());
}
};
for (Component child : spinner.getComponents()) {
if ("Spinner.nextButton".equals(child.getName())) {
((JButton) child).addActionListener(action);
}
if ("Spinner.previousButton".equals(child.getName())) {
((JButton) child).addActionListener(action);
}
}
关于java - 检测 JSpinner 按钮事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7673821/