JSlider问题:在leftclick之后的位置 [英] JSlider question: Position after leftclick

查看:108
本文介绍了JSlider问题:在leftclick之后的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我点击一个JSlider时,它会在点击方向上找到一个majorTick而不是跳到我实际点击的位置。 (如果滑块位于第47点,我点击5它将跳转到37而不是5)。有没有办法在使用JSliders时改变它,或者我是否必须使用另一个数据结构?

Whenever I click a JSlider it gets positioned one majorTick in the direction of the click instead of jumping to the spot I actually click. (If slider is at point 47 and I click 5 it'll jump to 37 instead of 5). Is there any way to change this while using JSliders, or do I have to use another datastructure?

推荐答案

这可能是奇怪的看起来,它实际上是控制这种行为的外观。看一下 BasicSliderUI ,你需要覆盖的方法是 scrollDueToClickInTrack(int)

As bizarre as this might seem, it's actually the Look and Feel which controls this behaviour. Take a look at BasicSliderUI, the method that you need to override is scrollDueToClickInTrack(int).

为了将 JSlider 的值设置为用户点击轨道的最近值,你需要在 getMousePosition()的鼠标坐标之间做一些花哨的裤子转换到有效的轨道值,同时考虑到的位置组件,它的方向,大小和刻度之间的距离。幸运的是, BasicSliderUI 为我们提供了两个方便的功能: valueForXPosition(int xPos) valueForYPosition(int yPos)

In order to set the value of the JSlider to the nearest value to where the user clicked on the track, you'd need to do some fancy pants translation between the mouse coordinates from getMousePosition() to a valid track value, taking into account the position of the Component, it's orientation, size and distance between ticks etc. Luckily, BasicSliderUI gives us two handy functions to do this: valueForXPosition(int xPos) and 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);
    }
});

这篇关于JSlider问题:在leftclick之后的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆