Using JSliders to size an oval. - Java Swing

Java examples for Swing:JSlider

Description

Using JSliders to size an oval.

Demo Code

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;

class OvalPanel extends JPanel {
  private int diameter = 10; // default diameter

  // draw an oval of the specified diameter
  @Override/*from  w w  w. j  a v  a  2  s . c om*/
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.fillOval(10, 10, diameter, diameter);
  }

  // validate and set diameter, then repaint
  public void setDiameter(int newDiameter) {
    // if diameter invalid, default to 10
    diameter = (newDiameter >= 0 ? newDiameter : 10);
    repaint(); // repaint panel
  }

  // used by layout manager to determine preferred size
  public Dimension getPreferredSize() {
    return new Dimension(200, 200);
  }

  // used by layout manager to determine minimum size
  public Dimension getMinimumSize() {
    return getPreferredSize();
  }
}

class SliderFrame extends JFrame {
  private final JSlider diameterJSlider; // slider to select diameter
  private final OvalPanel myPanel; // panel to draw circle

  // no-argument constructor
  public SliderFrame() {
    super("Slider Demo");

    myPanel = new OvalPanel(); // create panel to draw circle
    myPanel.setBackground(Color.YELLOW);

    // set up JSlider to control diameter value
    diameterJSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 200, 10);
    diameterJSlider.setMajorTickSpacing(10); // create tick every 10
    diameterJSlider.setPaintTicks(true); // paint ticks on slider

    // register JSlider event listener
    diameterJSlider.addChangeListener(e -> myPanel.setDiameter(diameterJSlider
        .getValue()));

    add(diameterJSlider, BorderLayout.SOUTH);
    add(myPanel, BorderLayout.CENTER);
  }
}

public class Main {
  public static void main(String[] args) {
    SliderFrame sliderFrame = new SliderFrame();
    sliderFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    sliderFrame.setSize(220, 270);
    sliderFrame.setVisible(true);
  }
}

Related Tutorials