Following is a simple example of how we can create and use a JSlider
in Java Swing to control a value. In this example, we’ll create a GUI application that has a slider and a label to display the current value selected by the slider:
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class JSliderDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGUI();
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("JSlider Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 150);
frame.setLayout(new FlowLayout());
// Create a label to display the slider value
JLabel valueLabel = new JLabel("Selected Value: 0");
frame.add(valueLabel);
// Create a slider
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
// Add a change listener to the slider
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
int selectedValue = slider.getValue();
valueLabel.setText("Selected Value: " + selectedValue);
}
});
frame.add(slider);
frame.setVisible(true);
}
}
Output: