Learning from masters
Learning from masters

Reputation: 2782

Changing the unit movement of a JSlider

I suppose this is a very silly question but I cannot figure out the solution/how to ask this to google. Basically, I want that my JSlider changes every X units each time an user clicks on it instead of 1 unit. How can I do it?

Upvotes: 0

Views: 208

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

As noted in the other answer, you need to

  1. set the minor tick spacing to how ever much you want it to move
  2. set the setSnapToTicks(true) so that the slider by default moves minor tick increments

e.g.,

final JSlider slider = new JSlider(0, 100, 50);
slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(20);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setSnapToTicks(true);

slider.addChangeListener(ce -> {
    System.out.println("value: " + slider.getValue());
});

JOptionPane.showMessageDialog(null, slider);

Upvotes: 1

Tommy Brettschneider
Tommy Brettschneider

Reputation: 1490

that's what I did in one of my apps... suppose it was setMinorTickSpacing()and setMajorTickSpacing():

JSlider jSlider1 = new JSlider();
jSlider1.setMajorTickSpacing(50);
jSlider1.setMaximum(500);
jSlider1.setMinimum(100);
jSlider1.setMinorTickSpacing(50);
jSlider1.setPaintLabels(true);
jSlider1.setPaintTicks(true);
jSlider1.setSnapToTicks(true);

Upvotes: 3

Related Questions