javacodex.com
Java Examples
Java Examples
memu home questions

JSlider

A JSlider lets you select a value graphically from a set of values between two integers by sliding a knob along a track. It has four important properties: an orientation, a minimum value, a maximum value, and a current value. The orientation determines whether it is displayed horizontally or vertically. You can use JSlider.VERTICAL and JSlider.HORIZONTAL as valid values for its orientation.

This example demonstrates how to add a ChangeListener to a JSlider.

Source: (SliderExample.java)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
 
public class SliderExample {
 
  public static void main(String[] arguments) {
 
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame f = new JFrame("JSlider Example");
    f.setSize(400,200);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
    JPanel container = new JPanel();
    container.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    container.setLayout(new GridLayout(2, 1));
 
 
    JPanel status = new JPanel(new FlowLayout());
    JLabel label = new JLabel("Value: ");
    final JTextField text = new JTextField(3);
 
    status.add(label);
    status.add(text);
 
 
    final JSlider slider = new JSlider(JSlider.HORIZONTAL,0,100,10);
    slider.setPreferredSize(new Dimension(150,20));
    slider.setMinorTickSpacing(5);  
    slider.setMajorTickSpacing(20);  
    slider.setPaintTicks(true);  
    slider.setPaintLabels(true);  
 
 
    slider.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        text.setText("" + slider.getValue());
      }
    });
 
    // set default value
    text.setText("" + slider.getValue());
 
    container.add(slider);
    container.add(status);
 
    f.add(container);
    f.setVisible(true);
 
  }
}
 

Output:

$ java SliderExample
Output



Contact: javacodex@yahoo.com