Java Swing How to - Set value to JSlider model








Question

We would like to know how to set value to JSlider model.

Answer

/*from w w  w  .j  a v a 2 s  .  c o m*/
import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JSlider;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JSlider oneJSlider = new JSlider();

    int newValue = 2;
    int newExtent = 10;
    int newMin = 0;
    int newMax = 10;
    oneJSlider.getModel().setRangeProperties(newValue, newExtent, newMin, newMax,
        true);
    int value = oneJSlider.getValue();
    System.out.println(value);
  
    oneJSlider.setPaintTicks(true);
    
    frame.add(oneJSlider, BorderLayout.NORTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}