问题
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