Java Program to set a spinner of dates in Java

Java 8Object Oriented ProgrammingProgramming

To set a spinner of dates, at first create a date object −

Date today = new Date();

Now, use SpinnerDateModel −

JSpinner spinner2 = new JSpinner(new SpinnerDateModel(today, null, null, Calendar.MONTH));

We will now consider a DateEditor, which is an editor for a JSpinner whose model is a SpinnerDateModel. Set the format for month here −

JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner2, "MM");
spinner2.setEditor(editor);

The following is an example to set a spinner of date 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("ResultID");
      JLabel label2 = new JLabel(" Appeared On (Month)");
      panel.setLayout(new GridBagLayout());
      int min = 0;
      int max = 10;
      int step = 1;
      int i = 3;
      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, "MM");
      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
Updated on 30-Jul-2019 22:30:26

Advertisements