How to create a date spinner in Java?

Java 8Object Oriented ProgrammingProgramming

To create a date spinner, use the SpinnerDateModel class. Within that set the date format −

Date today = new Date();
JSpinner spinner2 = new JSpinner(new SpinnerDateModel(today, null, null, Calendar.MONTH));
JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner2, "dd/MM/yy");
spinner2.setEditor(editor);

Above, we have set the Date format to be −

dd/MM/yy

The following is an example to create a date spinner in Java −

Example

package my;
import java.awt.GridBagLayout;
import java.util.Calendar;
import java.util.Date;
import javax.swing.*;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Spinner Demo");
      JPanel panel = new JPanel();
      JLabel label = new JLabel("Exam No.");
      JLabel label2 = new JLabel(" Appeared On");
      panel.setLayout(new GridBagLayout());
      int min = 0;
      int max = 10;
      int step = 1;
      int i = 5;
      SpinnerModel value = new SpinnerNumberModel(i, min, max, step);
      JSpinner spinner = new JSpinner(value);
      spinner.setBounds(50, 80, 70, 100);
      Date today = new Date();
      JSpinner spinner2 = new JSpinner(new SpinnerDateModel(today, null, null, Calendar.MONTH));
      JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner2, "dd/MM/yy");
      spinner2.setEditor(editor);
      panel.add(label);
      panel.add(spinner);
      panel.add(label2);
      panel.add(spinner2);
      frame.add(panel);
      frame.setSize(550,300);
      frame.setVisible(true);
   }
}

Output

raja
Published on 31-May-2019 15:49:24
Advertisements