MouseListener for JScrollBar arrow buttons

泄露秘密 提交于 2020-01-05 10:19:33

问题


http://s019.radikal.ru/i626/1203/ae/8420ef7757f7.png

    JScrollPane.getVerticalScrollBar().addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
                    System.out.println("mouseClicked");
        }
        public void mousePressed(MouseEvent e) {
                    System.out.println("mousePressed");
        }
        public void mouseReleased(MouseEvent e) {
                    System.out.println("mouseReleased");
        }
    });

It works if I click on the strip, but does not work when I click on the buttons


回答1:


The buttons are defined in the JScrollBar's UI so you need to extend the default UI implementation. Of course it is platform dependent. In my example I'll show you how to do it with BasicScrollBarUI. You can define a custom JScrollBar by calling the JScrollPane.setVerticalScrollBar(new CustomScrollBar()); In your CustomScrollBar you can do the following:

public class CustomScrollBar extends JScrollBar {
    public CustomScrollBar() {
        setUI(new CustomUI());
    }
    class CustomUI extends BasicScrollBarUI {
        @Override
        protected void installListeners() {
            super.installListeners();
            if (incrButton != null) {
                incrButton.addMouseListener(new MouseAdapter() {

                    @Override
                    public void mouseClicked(MouseEvent e) {
                        //Increment button is clicked!
                    }
                });
            }
            if (decrButton != null) {
                decrButton.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        //Decrement button is clicked!
                    }
               });
            }
        }
    }
}

I've tested it under XP but without a JScrollPane. I hope it helps!



来源:https://stackoverflow.com/questions/9863995/mouselistener-for-jscrollbar-arrow-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!