Close

Java Swing - Creating JSlider and Listening to ChangeEvent

[Updated: Apr 2, 2018, Created: Apr 2, 2018]

Following is a basic JSlider example. We will use JSlider to change the radius of a circle. We will also add ChangeListener for listening to value changes of the slider.

Example

public class JSliderExampleMain {
  public static void main(String[] args) {
      JFrame frame = createFrame();
      JSlider slider = createSlider();
      CirclePanel circlePanel = new CirclePanel();
      slider.addChangeListener(changeEvent -> {
          JSlider s = (JSlider) changeEvent.getSource();
          circlePanel.setRadius(s.getValue());
      });
      frame.add(slider, BorderLayout.NORTH);
      frame.add(circlePanel);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
  }

  private static JSlider createSlider() {
      JSlider slider = new JSlider();
      slider.setMaximum(100);
      slider.setValue(50);
      slider.setMajorTickSpacing(10);
      slider.setMinorTickSpacing(5);
      slider.setPaintTicks(true);
      slider.setPaintLabels(true);
      return slider;
  }

  private static JFrame createFrame() {
      JFrame frame = new JFrame("JSlider Basic example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(new Dimension(400, 300));
      return frame;
  }
}
public class CirclePanel extends JPanel {
  private int radius = 50;

  public CirclePanel() {
      setBorder(BorderFactory.createLineBorder(Color.GRAY, 3));
  }

  public void setRadius(int radius) {
      this.radius = radius;
      repaint();
  }

  @Override
  protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.setColor(Color.pink);
      g.fillOval(getWidth() / 2 - radius,
              getHeight() / 2 - radius,
              2 * radius, 2 * radius);
  }
}

Output

Example Project

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.3.9

JSlider example Select All Download
  • jslider-basic-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also