Java/Swing JFC/Slider

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

An example of JSlider with default labels

 
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly 
*/
// SwingSliderExample.java
// An example of JSlider with default labels.
//
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
public class SwingSliderExample extends JPanel {
  public SwingSliderExample() {
    super(true);
    this.setLayout(new BorderLayout());
    JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
    slider.setMinorTickSpacing(2);
    slider.setMajorTickSpacing(10);
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);
    // We"ll just use the standard numeric labels for now...
    slider.setLabelTable(slider.createStandardLabels(10));
    add(slider, BorderLayout.CENTER);
  }
  public static void main(String s[]) {
    JFrame frame = new JFrame("Slider Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new SwingSliderExample());
    frame.pack();
    frame.setVisible(true);
  }
}





A slider with tick marks and labels

 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JSlider;
public class Main extends JFrame {
  public static void main(String[] args) {
    new Main();
  }
  public Main() {
    Container content = getContentPane();
    content.setBackground(Color.white);
    JSlider slider1 = new JSlider();
    slider1.setBorder(BorderFactory.createTitledBorder("JSlider without Tick Marks"));
    content.add(slider1, BorderLayout.NORTH);
    JSlider slider2 = new JSlider();
    slider2.setBorder(BorderFactory.createTitledBorder("JSlider with Tick Marks"));
    slider2.setMajorTickSpacing(20);
    slider2.setMinorTickSpacing(5);
    slider2.setPaintTicks(true);
    content.add(slider2, BorderLayout.CENTER);
    JSlider slider3 = new JSlider();
    slider3.setBorder(BorderFactory.createTitledBorder("JSlider with Tick Marks & Labels"));
    slider3.setMajorTickSpacing(20);
    slider3.setMinorTickSpacing(5);
    slider3.setPaintTicks(true);
    slider3.setPaintLabels(true);
    content.add(slider3, BorderLayout.SOUTH);
    setSize(300,300);
    setVisible(true);
  }
}





Change the maximum value

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    int newMax = 256;
    slider.setMaximum(newMax);
  }
}





Change the minimum value

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    int newMin = 0;
    slider.setMinimum(newMin);
  }
}





Constraining JSlider Component Values to Tick Marks

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a horizontal slider that moves left-to-right
    JSlider slider = new JSlider();
    // Set major tick marks every 25 units
    int tickSpacing = 25;
    slider.setMajorTickSpacing(tickSpacing);
  }
}





Create a horizontal slider with custom min, max, and value

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    int initValue = 0;
    int minimum = 10;
    int maximum = 100;
    JSlider slider = new JSlider(minimum, maximum, initValue);
  }
}





Create a vertical slider with custom min, max, and value

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    int initValue = 0;
    int minimum = 10;
    int maximum = 100;
    JSlider slider = new JSlider(JSlider.VERTICAL, minimum, maximum, initValue);
  }
}





Create a vertical slider with min=0, max=100, value=50

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider(JSlider.VERTICAL);
  }
}





Creating a JSlider Component

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a horizontal slider with min=0, max=100, value=50
    JSlider slider = new JSlider();
    // Create a horizontal slider with custom min and max; value is set to the middle
    int minimum = -255;
    int maximum = 256;
    slider = new JSlider(minimum, maximum);
  }
}





Date slider

 

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ruponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class DateSlider extends JFrame {
  public final static Dimension RIGID_DIMENSION = new Dimension(1, 3);
  protected GregorianCalendar calendar = new GregorianCalendar();
  protected JLabel dateLabel;
  protected JSlider yearSlider = new JSlider(JSlider.HORIZONTAL, 1990, 2010, calendar
      .get(Calendar.YEAR));
  protected JSlider monthSlider = new JSlider(JSlider.HORIZONTAL, 1, 12, calendar
      .get(Calendar.MONTH) + 1);
  protected JSlider daySlider;
  protected Hashtable hashTable;
  protected SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yyyyy");
  public DateSlider() {
    super("Date Slider");
    setSize(500, 340);
    Date currentDate = new Date();
    calendar.setTime(currentDate);
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(4, 1));
    JPanel p = new JPanel();
    p.setBorder(new TitledBorder(new EtchedBorder(), "Selected Date"));
    dateLabel = new JLabel(dateFormat.format(currentDate) + "     ");
    dateLabel.setFont(new Font("Arial", Font.BOLD, 24));
    p.add(dateLabel);
    p1.add(p);
    yearSlider.setPaintLabels(true);
    yearSlider.setMajorTickSpacing(5);
    yearSlider.setMinorTickSpacing(1);
    yearSlider.setPaintTicks(true);
    DateListener lst = new DateListener();
    yearSlider.addChangeListener(lst);
    p = new JPanel();
    p.setBorder(new TitledBorder(new EtchedBorder(), "Year"));
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    p.add(Box.createRigidArea(RIGID_DIMENSION));
    p.add(yearSlider);
    p.add(Box.createRigidArea(RIGID_DIMENSION));
    p1.add(p);
    String[] months = (new DateFormatSymbols()).getShortMonths();
    hashTable = new Hashtable(12);
    for (int i = 0; i < 12; i++)
      hashTable.put(new Integer(i + 1), new JLabel(months[i],
          JLabel.CENTER));
    monthSlider.setLabelTable(hashTable);
    monthSlider.setPaintLabels(true);
    monthSlider.setMajorTickSpacing(1);
    monthSlider.setPaintTicks(true);
    monthSlider.addChangeListener(lst);
    p = new JPanel();
    p.setBorder(new TitledBorder(new EtchedBorder(), "Month"));
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    p.add(Box.createRigidArea(RIGID_DIMENSION));
    p.add(monthSlider);
    p.add(Box.createRigidArea(RIGID_DIMENSION));
    p1.add(p);
    int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    daySlider = new JSlider(JSlider.HORIZONTAL, 1, maxDays, calendar
        .get(Calendar.DAY_OF_MONTH));
    daySlider.setPaintLabels(true);
    daySlider.setMajorTickSpacing(5);
    daySlider.setMinorTickSpacing(1);
    daySlider.setPaintTicks(true);
    daySlider.addChangeListener(lst);
    p = new JPanel();
    p.setBorder(new TitledBorder(new EtchedBorder(), "Day"));
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    p.add(Box.createRigidArea(RIGID_DIMENSION));
    p.add(daySlider);
    p.add(Box.createRigidArea(RIGID_DIMENSION));
    p1.add(p);
    getContentPane().add(p1, BorderLayout.CENTER);
    WindowListener wndCloser = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    };
    addWindowListener(wndCloser);
    enableEvents(ComponentEvent.ruPONENT_RESIZED);
    setVisible(true);
  }
  protected void processComponentEvent(ComponentEvent e) {
    if (e.getID() == ComponentEvent.ruPONENT_RESIZED) {
      int w = getSize().width;
      yearSlider.setLabelTable(null);
      if (w > 200)
        yearSlider.setMajorTickSpacing(5);
      else
        yearSlider.setMajorTickSpacing(10);
      yearSlider.setPaintLabels(w > 100);
      monthSlider.setLabelTable(w > 300 ? hashTable : null);
      if (w <= 300 && w >= 200)
        monthSlider.setMajorTickSpacing(1);
      else
        monthSlider.setMajorTickSpacing(2);
      monthSlider.setPaintLabels(w > 100);
      daySlider.setLabelTable(null);
      if (w > 200)
        daySlider.setMajorTickSpacing(5);
      else
        daySlider.setMajorTickSpacing(10);
      daySlider.setPaintLabels(w > 100);
    }
  }
  public void showDate() {
    calendar.set(yearSlider.getValue(), monthSlider.getValue() - 1, 1);
    int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    if (daySlider.getMaximum() != maxDays) {
      daySlider.setValue(Math.min(daySlider.getValue(), maxDays));
      daySlider.setMaximum(maxDays);
      daySlider.repaint();
    }
    calendar.set(yearSlider.getValue(), monthSlider.getValue() - 1, daySlider
        .getValue());
    Date date = calendar.getTime();
    dateLabel.setText(dateFormat.format(date));
  }
  class DateListener implements ChangeListener {
    public void stateChanged(ChangeEvent e) {
      showDate();
    }
  }
  public static void main(String argv[]) {
    new DateSlider();
  }
}





Determine if currently painting labels

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    boolean b = slider.getPaintLabels(); 
    // Paint labels at the major ticks - 0, 25, 50, 75, and 100
    slider.setPaintLabels(true);
  }
}





Determine if currently snapping to tick marks

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a horizontal slider that moves left-to-right
    JSlider slider = new JSlider();
    boolean b = slider.getSnapToTicks(); // false
  }
}





Drawing with Swing, using a JSlider

 
// : c14:SineWave.java
// Drawing with Swing, using a JSlider.
// <applet code=SineWave width=700 height=400></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class SineDraw extends JPanel {
  private static final int SCALEFACTOR = 200;
  private int cycles;
  private int points;
  private double[] sines;
  private int[] pts;
  public SineDraw() {
    setCycles(5);
  }
  public void setCycles(int newCycles) {
    cycles = newCycles;
    points = SCALEFACTOR * cycles * 2;
    sines = new double[points];
    for (int i = 0; i < points; i++) {
      double radians = (Math.PI / SCALEFACTOR) * i;
      sines[i] = Math.sin(radians);
    }
    repaint();
  }
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    int maxWidth = getWidth();
    double hstep = (double) maxWidth / (double) points;
    int maxHeight = getHeight();
    pts = new int[points];
    for (int i = 0; i < points; i++)
      pts[i] = (int) (sines[i] * maxHeight / 2 * .95 + maxHeight / 2);
    g.setColor(Color.RED);
    for (int i = 1; i < points; i++) {
      int x1 = (int) ((i - 1) * hstep);
      int x2 = (int) (i * hstep);
      int y1 = pts[i - 1];
      int y2 = pts[i];
      g.drawLine(x1, y1, x2, y2);
    }
  }
}
public class SineWave extends JApplet {
  private SineDraw sines = new SineDraw();
  private JSlider adjustCycles = new JSlider(1, 30, 5);
  public void init() {
    Container cp = getContentPane();
    cp.add(sines);
    adjustCycles.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        sines.setCycles(((JSlider) e.getSource()).getValue());
      }
    });
    cp.add(BorderLayout.SOUTH, adjustCycles);
  }
  public static void main(String[] args) {
    run(new SineWave(), 700, 400);
  }
  public static void run(JApplet applet, int width, int height) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(applet);
    frame.setSize(width, height);
    applet.init();
    applet.start();
    frame.setVisible(true);
  }
} ///:~





Get the extent

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    int extent = slider.getExtent();
  }
}





Getting and Setting the Values of a JSlider Component

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    // Get the current value
    int value = slider.getValue();
    // Get the minimum value
    int min = slider.getMinimum();
    // Get the maximum value
    int max = slider.getMaximum();
  }
}





Hide the track

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    slider.setPaintTrack(false);
  }
}





Inverted Sliders

 
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JSlider;
public class InvertedSliders {
  public static void main(String args[]) {
    JFrame f = new JFrame("Inverted Sliders");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JSlider js1 = new JSlider();
    js1.setMajorTickSpacing(10);
    js1.setPaintTicks(true);
    js1.setPaintLabels(true);
    JSlider js2 = new JSlider();
    js2.setInverted(true);
    js2.setMajorTickSpacing(10);
    js2.setPaintTicks(true);
    js2.setPaintLabels(true);
    JSlider js3 = new JSlider(JSlider.VERTICAL);
    js3.setPaintTrack(false);
    js3.setMajorTickSpacing(10);
    js3.setPaintTicks(true);
    js3.setPaintLabels(true);
    JSlider js4 = new JSlider(JSlider.VERTICAL);
    js4.setInverted(true);
    js4.setMajorTickSpacing(10);
    js4.setPaintTicks(true);
    js4.setPaintLabels(true);
    Container c = f.getContentPane();
    c.add(js1, BorderLayout.NORTH);
    c.add(js2, BorderLayout.SOUTH);
    c.add(js3, BorderLayout.EAST);
    c.add(js4, BorderLayout.WEST);
    f.setSize(300, 250);
    f.setVisible(true);
  }
}





JSlider Sample 2

 
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JSlider;
public class JSliderSample {
  public static void main(String args[]) {
    JFrame f = new JFrame("JSlider Sample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = f.getContentPane();
    JSlider slider = new JSlider();
    slider.setMinorTickSpacing(5);
    slider.setMajorTickSpacing(10);
    slider.setPaintTicks(true);
    slider.setSnapToTicks(true);
    slider.setPaintTrack(false);
    slider.setPaintLabels(true);
    slider.setToolTipText("The value is 50");
    content.add(slider, BorderLayout.CENTER);
    f.setSize(300, 100);
    f.setVisible(true);
  }
}





Listening for Value Changes in a JSlider Component

 
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    slider.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent evt) {
        JSlider slider = (JSlider) evt.getSource();
        if (!slider.getValueIsAdjusting()) {
          int value = slider.getValue();
          System.out.println(value);
        }
      }
    });
  }
}





Make it vertical and move bottom-to-top

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    slider.setOrientation(JSlider.VERTICAL);
    slider.setInverted(false);
  }
}





Make it vertical and move top-to-bottom

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    slider.setOrientation(JSlider.VERTICAL);
    slider.setInverted(true);
  }
}





Make the horizontal slider move right-to-left

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    slider.setInverted(true);
  }
}





Move the slider by a fixed amount: the extent.

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    // Set an extent
    int extent = 10;
    slider.setExtent(extent);
  }
}





Sample Sliders

 
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Polygon;
import java.util.Hashtable;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;
public class SampleSliders {
  public static void main(String args[]) {
    String title = (args.length == 0 ? "Sample Slider" : args[0]);
    JFrame f = new JFrame(title);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JSlider js1 = new JSlider();
    js1.putClientProperty("JSlider.isFilled", Boolean.TRUE);
    JSlider js2 = new JSlider();
    js2.setMajorTickSpacing(25);
    js2.setPaintTicks(true);
    js2.setSnapToTicks(true);
    JSlider js3 = new JSlider(JSlider.VERTICAL);
    js3.setPaintTrack(false);
    js3.setMinorTickSpacing(5);
    js3.setMajorTickSpacing(10);
    js3.setPaintTicks(true);
    js3.setPaintLabels(true);
    js3.setSnapToTicks(true);
    JSlider js4 = new JSlider(JSlider.VERTICAL);
    Hashtable table = new Hashtable();
    table.put(new Integer(0), new JLabel(new DiamondIcon(Color.red)));
    table.put(new Integer(10), new JLabel("Ten"));
    table.put(new Integer(25), new JLabel("Twenty-Five"));
    table.put(new Integer(34), new JLabel("Thirty-Four"));
    table.put(new Integer(52), new JLabel("Fifty-Two"));
    table.put(new Integer(70), new JLabel("Seventy"));
    table.put(new Integer(82), new JLabel("Eighty-Two"));
    table.put(new Integer(100), new JLabel(new DiamondIcon(Color.black)));
    js4.setLabelTable(table);
    js4.setPaintLabels(true);
    js4.setSnapToTicks(true);
    Container c = f.getContentPane();
    c.add(js1, BorderLayout.NORTH);
    c.add(js2, BorderLayout.SOUTH);
    c.add(js3, BorderLayout.WEST);
    c.add(js4, BorderLayout.EAST);
    f.setSize(300, 200);
    f.setVisible(true);
  }
}
class DiamondIcon implements Icon {
  private Color color;
  private boolean selected;
  private int width;
  private int height;
  private Polygon poly;
  private static final int DEFAULT_WIDTH = 10;
  private static final int DEFAULT_HEIGHT = 10;
  public DiamondIcon(Color color) {
    this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT);
  }
  public DiamondIcon(Color color, boolean selected) {
    this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT);
  }
  public DiamondIcon(Color color, boolean selected, int width, int height) {
    this.color = color;
    this.selected = selected;
    this.width = width;
    this.height = height;
    initPolygon();
  }
  private void initPolygon() {
    poly = new Polygon();
    int halfWidth = width / 2;
    int halfHeight = height / 2;
    poly.addPoint(0, halfHeight);
    poly.addPoint(halfWidth, 0);
    poly.addPoint(width, halfHeight);
    poly.addPoint(halfWidth, height);
  }
  public int getIconHeight() {
    return height;
  }
  public int getIconWidth() {
    return width;
  }
  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.setColor(color);
    g.translate(x, y);
    if (selected) {
      g.fillPolygon(poly);
    } else {
      g.drawPolygon(poly);
    }
    g.translate(-x, -y);
  }
}





Scroll Slider

 
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;  
public class ScrollSlider {
  public static void main(String args[]) {
    JFrame f = new JFrame("Change Slider");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JSlider aJSlider = new JSlider (JSlider.HORIZONTAL, 0, 1000, 500);
    ChangeListener aChangeListener = new BoundedChangeListener();
    aJSlider.addChangeListener(aChangeListener);
    Container c = f.getContentPane();
    c.add (aJSlider, BorderLayout.SOUTH);
    f.setSize (300, 200);
    f.setVisible (true);
  }
}
class BoundedChangeListener implements ChangeListener {
  public void stateChanged(ChangeEvent changeEvent) {
    Object source = changeEvent.getSource();
    if (source instanceof BoundedRangeModel) {
      BoundedRangeModel aModel = (BoundedRangeModel) source;
      if (!aModel.getValueIsAdjusting()) {
        System.out.println("Changed: " + aModel.getValue());
      }
    } else if (source instanceof JSlider) {
      JSlider theJSlider = (JSlider) source;
      if (!theJSlider.getValueIsAdjusting()) {
        System.out.println("Slider changed: " + theJSlider.getValue());
      }
    } else if (source instanceof JProgressBar) {
      JProgressBar theJProgressBar = (JProgressBar) source;
      System.out.println("ProgressBar changed: "
          + theJProgressBar.getValue());
    } else {
      System.out.println("Something changed: " + source);
    }
  }
}





Set all the values at once by using the model

 

import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    int newValue = 2;
    int newExtent = 10;
    int newMin = 0;
    int newMax = 10;
    slider.getModel().setRangeProperties(newValue, newExtent, newMin, newMax,
        false);
  }
}





Set major tick marks every 25 units

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a horizontal slider that moves left-to-right
    JSlider slider = new JSlider();
    int tickSpacing = 25;
    slider.setMajorTickSpacing(tickSpacing);
  }
}





Set minor tick marks every 5 units

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a horizontal slider that moves left-to-right
    JSlider slider = new JSlider();
    int tickSpacing = 5;
    slider.setMinorTickSpacing(tickSpacing);
  }
}





Set the extent

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    int newExtent = 10;
    slider.setExtent(newExtent);
  }
}





Set the value; the new value will be forced into the bar"s range

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    int newValue = 33;
    slider.setValue(newValue);
  }
}





Set to a spot between tick marks; the value moves to closest tick mark

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    slider.setValue(27);
    int value = slider.getValue();
  }
}





Showing Tick-Mark Labels on a JSlider Component

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    // Set major tick marks every 25 units
    int tickSpacing = 25;
    slider.setMajorTickSpacing(tickSpacing);
  }
}





Showing Tick Marks on a JSlider Component

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a horizontal slider that moves left-to-right
    JSlider slider = new JSlider();
    // Determine if currently showing ticks
    boolean b = slider.getPaintTicks(); // false
  }
}





Show tick marks

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a horizontal slider that moves left-to-right
    JSlider slider = new JSlider();
    slider.setPaintTicks(true);
  }
}





Slider change action listener

 
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderDemo extends JFrame {
  protected JLabel label;
  protected JSlider slider;
  public SliderDemo() {
    init();
  }
  public void init() {
    getContentPane().setLayout(new FlowLayout());
    JPanel p0 = new JPanel();
    p0.setLayout(new BoxLayout(p0, BoxLayout.X_AXIS));
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(3, 1));
    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
    label = new JLabel("101.5 FM");
    label.setFont(new Font("Arial", Font.BOLD, 24));
    p.add(label);
    p1.add(p);
    slider = new JSlider(JSlider.HORIZONTAL, 1, 5, 1);
    slider.setPaintLabels(true);
    slider.setMajorTickSpacing(5);
    MyChangeListener lst = new MyChangeListener();
    slider.addChangeListener(lst);
    p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    p.add(slider);
    p1.add(p);
    p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    JPanel p2 = new JPanel();
    p2.setLayout(new BoxLayout(p2, BoxLayout.X_AXIS));
    for (int k = 1; k <= 5; k++) {
      JButton fv = new JButton(Integer.toString(k));
      fv.addActionListener(new MyActionListener(k));
      p2.add(fv);
    }
    p.add(p2);
    p1.add(p);
    p0.add(p1);
    p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
    p0.add(p);
    getContentPane().add(p0);
    lst.stateChanged(new ChangeEvent(slider));
  }
  public synchronized void playStation(int index) {
    slider.setValue(index);
  }
  class MyActionListener implements ActionListener {
    protected int m_index;
    MyActionListener(int index) {
      m_index = index;
    }
    public void actionPerformed(ActionEvent e) {
      playStation(m_index);
    }
  }
  class MyChangeListener implements ChangeListener {
    MyChangeListener() {
    }
    public synchronized void stateChanged(ChangeEvent e) {
      int frequency = slider.getValue();
      label.setText(frequency + " FM");
    }
  }
  public static void main(String[] za) {
    SliderDemo d = new SliderDemo();
    d.setSize(400, 200);
    d.show();
  }
}





Slider ChangeListener

 
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.BoundedRangeModel;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ChangeSlider {
  public static void main(String args[]) {
    JFrame f = new JFrame("Change Slider");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JSlider aJSlider = new JSlider(JSlider.HORIZONTAL);
    ChangeListener aChangeListener = new BoundedChangeListener();
    BoundedRangeModel model = aJSlider.getModel();
    model.addChangeListener(aChangeListener);
    aJSlider.addChangeListener(aChangeListener);
    Container c = f.getContentPane();
    c.add(aJSlider, BorderLayout.SOUTH);
    f.setSize(300, 200);
    f.setVisible(true);
  }
}
class BoundedChangeListener implements ChangeListener {
  public void stateChanged(ChangeEvent changeEvent) {
    Object source = changeEvent.getSource();
    if (source instanceof BoundedRangeModel) {
      BoundedRangeModel aModel = (BoundedRangeModel) source;
      if (!aModel.getValueIsAdjusting()) {
        System.out.println("Changed: " + aModel.getValue());
      }
    } else if (source instanceof JSlider) {
      JSlider theJSlider = (JSlider) source;
      if (!theJSlider.getValueIsAdjusting()) {
        System.out.println("Slider changed: " + theJSlider.getValue());
      }
    } else if (source instanceof JProgressBar) {
      JProgressBar theJProgressBar = (JProgressBar) source;
      System.out.println("ProgressBar changed: "
          + theJProgressBar.getValue());
    } else {
      System.out.println("Something changed: " + source);
    }
  }
}





Slider Sample

 
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JSlider;
public class SliderSample {
  public static void main(String args[]) {
    JFrame f = new JFrame("JSlider Sample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = f.getContentPane();
    JSlider slider = new JSlider();
    slider.setMinorTickSpacing(5);
    slider.setMajorTickSpacing(10);
    slider.setPaintTicks(true);
    slider.setSnapToTicks(true);
    slider.setPaintTrack(false);
    slider.setPaintLabels(true);
    content.add(slider, BorderLayout.CENTER);
    f.setSize(300, 100);
    f.setVisible(true);
  }
}





Snap to tick marks

 
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a horizontal slider that moves left-to-right
    JSlider slider = new JSlider();
    slider.setSnapToTicks(true);
  }
}





Text Slider

 
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoundedRangeModel;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JTextField;
public class TextSlider extends JPanel {
  private JTextField textField;
  private JScrollBar scrollBar;
  public TextSlider() {
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    textField = new JTextField();
    scrollBar = new JScrollBar(JScrollBar.HORIZONTAL);
    BoundedRangeModel brm = textField.getHorizontalVisibility();
    scrollBar.setModel(brm);
    add(textField);
    add(scrollBar);
  }
  public JTextField getTextField() {
    return textField;
  }
  public String getText() {
    return textField.getText();
  }
  public void addActionListener(ActionListener l) {
    textField.addActionListener(l);
  }
  public void removeActionListener(ActionListener l) {
    textField.removeActionListener(l);
  }
  public JScrollBar getScrollBar() {
    return scrollBar;
  }
  public static void main(String args[]) {
    JFrame f = new JFrame("Text Slider");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final TextSlider ts = new TextSlider();
    ts.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Text: " + ts.getText());
      }
    });
    Container c = f.getContentPane();
    c.add(ts, BorderLayout.NORTH);
    f.setSize(300, 200);
    f.setVisible(true);
  }
}





The slider allows you to use an arbitrary label at any particular major tick mark.

 
import java.util.Dictionary;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JSlider;
public class Main {
  public static void main(String[] argv) throws Exception {
    JSlider slider = new JSlider();
    
    Dictionary table = slider.getLabelTable();
    ImageIcon icon = new ImageIcon("icon.gif");
    JLabel label = new JLabel(icon);
    // Set at desired positions
    table.put(new Integer(slider.getMinimum()), label);
    table.put(new Integer(slider.getMaximum()), label);
    // Force the slider to use the new labels
    slider.setLabelTable(table);
  }
}





Tick Sliders

 
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JSlider;
public class TickSliders {
  public static void main(String args[]) {
    JFrame f = new JFrame("Tick Slider");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // No Ticks
    JSlider jSliderOne = new JSlider();
    // Major Tick 25 - Minor 5
    JSlider jSliderTwo = new JSlider();
    jSliderTwo.setMinorTickSpacing(5);
    jSliderTwo.setMajorTickSpacing(25);
    jSliderTwo.setPaintTicks(true);
    jSliderTwo.setSnapToTicks(true);
    // Major Tick 25 - Minor 6
    JSlider jSliderThree = new JSlider(JSlider.VERTICAL);
    jSliderThree.setMinorTickSpacing(6);
    jSliderThree.setMajorTickSpacing(25);
    jSliderThree.setPaintTicks(true);
    JSlider jSliderFour = new JSlider(JSlider.VERTICAL);
    // Major Tick 25 - Minor 1
    jSliderFour.setMinorTickSpacing(1);
    jSliderFour.setMajorTickSpacing(25);
    jSliderFour.setPaintTicks(true);
    Container c = f.getContentPane();
    c.add(jSliderOne, BorderLayout.NORTH);
    c.add(jSliderTwo, BorderLayout.SOUTH);
    c.add(jSliderThree, BorderLayout.WEST);
    c.add(jSliderFour, BorderLayout.EAST);
    f.setSize(300, 200);
    f.setVisible(true);
  }
}





Using progress bars and sliders

 
// : c14:Progress.java
// Using progress bars and sliders.
// <applet code=Progress width=300 height=200></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.JSlider;
import javax.swing.border.TitledBorder;
public class Progress extends JApplet {
  private JProgressBar pb = new JProgressBar();
  private JSlider sb = new JSlider(JSlider.HORIZONTAL, 0, 100, 60);
  public void init() {
    Container cp = getContentPane();
    cp.setLayout(new GridLayout(2, 1));
    cp.add(pb);
    sb.setValue(0);
    sb.setPaintTicks(true);
    sb.setMajorTickSpacing(20);
    sb.setMinorTickSpacing(5);
    sb.setBorder(new TitledBorder("Slide Me"));
    pb.setModel(sb.getModel()); // Share model
    cp.add(sb);
  }
  public static void main(String[] args) {
    run(new Progress(), 300, 200);
  }
  public static void run(JApplet applet, int width, int height) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(applet);
    frame.setSize(width, height);
    applet.init();
    applet.start();
    frame.setVisible(true);
  }
} ///:~