开发者

Detecting JSpinner button events

开发者 https://www.devze.com 2023-04-11 08:29 出处:网络
I need to create some JSpinner controls where I can detect the button presses, whilst using the current look and feel. I have found I can do this easily enough as follows:

I need to create some JSpinner controls where I can detect the button presses, whilst using the current look and feel. I have found I can do this easily enough as follows:

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

    @Override
    protected Component createPreviousButton() {
        // Add custom ActionListener.
    }
}

The problem is that by doing this I end up with a nasty-looking spinner which doesn't use the same look 开发者_开发技巧and feel as the rest of my UI. I'm currently using Nimbus but I need to support different L&F configurations.

I thought about possibly setting up some sort of dynamic proxy, but couldn't find any suitable Spinner interfaces to enable me to do that.

Can anyone think of a way around the problem? I figure I either need to get at the button ActionListeners without subclassing BasicSpinnerUI, or work out a way to have my CustomSpinnerUI use the correct L&F.

Edit: "default look and feel" -> "current look and feel".


a dirty technical answer to (concededly assumed) problem "how to access the buttons for hooking-in a custom actionListener" is to loop through the spinner's children and add the listeners to the buttons, identified by their name:

    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);
        }
    }
  • that's dirty because it relies on an undocumented implementation detail which a LAF may or may not respect: Metal, Nimbus do; Win doesnt (which I consider an oversight but that's a different story :-)
  • it is technical only, as the real problem seems to be somewhere else, judging by a recent comment on the question
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号