当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How to differentiate between setValue and clicking arrow buttons in a JScrollBar?

问题描述:

I use a simple JScrollbar for my app for controlling the visible part of a drawing in a JPanel. Every time I move the view port I use the setValue method of the scroll-bar, and every time I drag the scroll-bar I move the view port.

This is the basic code:

public void adjustmentValueChanged(AdjustmentEvent event) {

JScrollBar scrollbar = ((JScrollBar) event.getSource());

if (scrollbar.getValueIsAdjusting()) {

_panel.moveViewport(scrollbar.getValue(), 0);

}

}

And when I programmatically change the view port I use the method moveViewport

 public void moveViewport(int x, int y) {

/* change the viewport */

_scrollbar.setValue(x)

}

All works fine. I use getValueIsAdjusting to differentiate when the value was changed from the setValue and the drag of the knob.

My problem is when I try to use the unitIncrement buttons. When I press a button, the event is the same as when I call scrollbar.setValue. So if I change the if (event.getValueIsAdjusting) to accept the click, it will accept the setValue and it starts a recursion.

What is the design pattern in this case? Is the only answer to extend scroll-bars as in MouseListener for JScrollBar arrow buttons?

Please, do not tell me to use JScrollPane. I can not use it for other reasons. But I think that everything a scroll pane can do I could do with a JScrollBar.

EDIT: I think I fixed it... but I do not understand how!!! I used removed the getIsValueIsAdjusting and used the SwingUtilities.invokeLater (thanks to this question) and now I can press the buttons without recursion. So my new question is "why it works?"

分享给朋友:
您可能感兴趣的文章:
随机阅读: