检测JSpinner按钮事件

vau*_*oid 1 java swing look-and-feel jbutton jspinner

我需要创建一些JSpinner控件,我可以检测按钮按下,同时使用当前的外观.我发现我可以轻松地做到这一点,如下所示:

class CustomSpinnerUI extends BasicSpinnerUI {
    @Override
    protected Component createNextButton() {
        // Add custom ActionListener.
    }

    @Override
    protected Component createPreviousButton() {
        // Add custom ActionListener.
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,通过这样做,我最终得到一个看起来很讨厌的微调器,它不会像我的UI的其余部分那样使用相同的外观和感觉.我目前正在使用,Nimbus但我需要支持不同的L&F配置.

我想过可能会设置某种动态代理,但找不到任何合适的Spinner接口来让我这样做.

任何人都可以想到解决这个问题的方法吗?我想我要么在ActionListeners没有子类化的情况下得到按钮BasicSpinnerUI,要么想办法让我CustomSpinnerUI使用正确的L&F.

编辑:"默认外观" - >"当前外观".

kle*_*tra 5

一个肮脏的技术答案(承认假设)问题"如何访问用于挂钩自定义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);
        }
    }
Run Code Online (Sandbox Code Playgroud)
  • 这很脏,因为它依赖于LAF可能会或可能不会尊重的无证实施细节:Metal,Nimbus do; 胜利没有(我认为这是一个疏忽,但这是一个不同的故事:-)
  • 它是技术性的,因为真正的问题似乎在其他地方,从最近对该问题的评论来判断