Java JSpinner.DateEditor

Introduction

We can set up JSpinner with an editor object to display the current value.

JSpinner has the following three static inner classes to display three different kinds of ordered lists:

  • JSpinner.NumberEditor
  • JSpinner.DateEditor
  • JSpinner.ListEditor
import java.awt.FlowLayout;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;

public class Main extends JFrame {
   public Main() {
      super("java2s.com");

      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setLayout(new FlowLayout());

      Calendar calendar = Calendar.getInstance();
      calendar.set(1950, 1, 1);/* w  w w.  ja v a  2  s.c om*/
      Date minValue = calendar.getTime();
      calendar.set(2050, 12, 31);
      Date maxValue = calendar.getTime();
      Date currentValue = new Date();
      int steps = Calendar.DAY_OF_MONTH; // Must be a Calendar field
      SpinnerDateModel dModel = new SpinnerDateModel(currentValue, minValue,
          maxValue, steps);
      JSpinner spinner = new JSpinner(dModel);

      JSpinner.DateEditor dEditor = new JSpinner.DateEditor(spinner, "mm/dd/yyyy");
      spinner.setEditor(dEditor);
      
      getContentPane().add(spinner);
   }

   public static void main(String[] args) {
      Main frame = new Main();
      frame.pack();
      frame.setVisible(true);
   }
}



PreviousNext

Related