Java JSpinner get editor as JFormattedTextField

Description

Java JSpinner get editor as JFormattedTextField

import java.awt.FlowLayout;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;

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

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

      Calendar calendar = new GregorianCalendar();
      calendar.set(Calendar.HOUR_OF_DAY, 13); // 1pm

      SpinnerDateModel dateModel = new SpinnerDateModel(calendar.getTime(), null,
          null, Calendar.HOUR_OF_DAY);
      JSpinner spinner = new JSpinner(dateModel);

      JFormattedTextField tf = ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
      DefaultFormatterFactory factory = (DefaultFormatterFactory) tf.getFormatterFactory();
      DateFormatter formatter = (DateFormatter) factory.getDefaultFormatter();

      // Change the date format to only show the hours
      formatter.setFormat(new SimpleDateFormat("hh:00 a"));
      /*from   w  w w.j  a v  a 2s  .co  m*/
      getContentPane().add(spinner);
   }

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



PreviousNext

Related