用于JScrollBar箭头按钮的MouseListener

时间:2012-03-25 20:57:45

标签: java button mouselistener jscrollbar

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");
        }
    });

如果我点击条带,它会起作用,但是当我点击按钮

时它不起作用

1 个答案:

答案 0 :(得分:1)

按钮在JScrollBar的UI中定义,因此您需要扩展默认的UI实现。当然它取决于平台。在我的示例中,我将向您展示如何使用BasicScrollBarUI执行此操作。 您可以通过调用JScrollPane.setVerticalScrollBar(new CustomScrollBar());来定义自定义JScrollBar 在CustomScrollBar中,您可以执行以下操作:

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!
                    }
               });
            }
        }
    }
}

我在XP下测试了它但没有JScrollPane。 我希望它有所帮助!