CodeGuy
CodeGuy

Reputation: 28907

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?

Upvotes: 2

Views: 2513

Answers (2)

clic
clic

Reputation: 385

BasicSliderUI provides a method called valueForXPosition:

Returns the value at the x position. If xPos is beyond the track at the left or the right, this method sets the value to either the minimum or maximum value of the slider, depending on if the slider is inverted or not.

(For vertical sliders use valueForYPosition)

Example adding a MouseListener to a horizontal JSlider using valueForXPosition:

JSlider slider = new JSlider();
slider.setOrientation(JSlider.HORIZONTAL);
slider.setMinimum(0);
slider.setMaximum(100); 
slider.addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
       JSlider sourceSlider=(JSlider)e.getSource();
       BasicSliderUI ui = (BasicSliderUI)sourceSlider.getUI();
       int value = ui.valueForXPosition( e.getX() );
       slider.setValue(value);
    }
});

Upvotes: 3

jjnguy
jjnguy

Reputation: 138874

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.)

Upvotes: 3

Related Questions