E. *_*all 13 java user-interface swing jslider
每当我点击一个JSlider时,它会在点击方向上找到一个majorTick而不是跳到我实际点击的位置.(如果滑块位于第47点,我点击5,它将跳转到37而不是5).有没有办法在使用JSliders时改变这个,或者我是否必须使用另一个数据结构?
nin*_*ded 17
尽管看起来很奇怪,但它实际上是控制这种行为的外观.看一下BasicSliderUI,你需要覆盖的方法是scrollDueToClickInTrack(int).
为了将值设置为JSlider用户在轨道上单击的最近值,您需要在鼠标坐标getMousePosition()到有效轨道值之间进行一些花哨的裤子转换,同时考虑到它的位置Component,它的方向,大小和刻度之间的距离等.幸运的是,BasicSliderUI为我们提供了两个方便的功能:valueForXPosition(int xPos)和valueForYPosition(int yPos):
JSlider slider = new JSlider(JSlider.HORIZONTAL);
slider.setUI(new MetalSliderUI() {
protected void scrollDueToClickInTrack(int direction) {
// this is the default behaviour, let's comment that out
//scrollByBlock(direction);
int value = slider.getValue();
if (slider.getOrientation() == JSlider.HORIZONTAL) {
value = this.valueForXPosition(slider.getMousePosition().x);
} else if (slider.getOrientation() == JSlider.VERTICAL) {
value = this.valueForYPosition(slider.getMousePosition().y);
}
slider.setValue(value);
}
});
Run Code Online (Sandbox Code Playgroud)