javaswingjcomponentjslider

JSlider - clicking makes the dot go towards that direction


I have a JSlider with minimum value of 0 and max value of 100. When the JSlider first launches, the value is 0.

Now, when I click my mouse on the 50, or even the 20 or 100, the JSlider doesn't move to the location I click. It simply jumps a little bit towards the right.

How do I make it so that the value will go to whatever I click?


Solution

  • Here is the beginning of a class that will do what you need.

    The general idea is to detect where the user clicks and calculate the value offset necessary in order to match that new slider location.

    // 'E' stands for enhanced
    public class EJSlider extends JSlider {
    
       public EJSlider() {
          super();
          addMouseListener(new MouseAdapter() {
             @Override
             public void mousePressed(MouseEvent e) {
                Point p = e.getPoint();
                double percent = p.x / ((double) getWidth());
                int range = getMaximum() - getMinimum();
                double newVal = range * percent;
                int result = (int)(getMinimum() + newVal);
                setValue(result);
             }
          });
       }
    
       public static void main(String[] args) {
          JFrame f = new JFrame();
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.add(new EJSlider());
          f.pack();
          f.setVisible(true);
       }
    }
    

    Simply run the example. The slider will jump to wherever you click your mouse. This has not been thoroughly tested, and will not work with vertical sliders, yet.

    A similar solution to this one would be simply adding my custom MouseListener to any JSlider you would like that functionality on.

    (Note, I know it's not perfect yet, but it is a good start.)