Java by API/javax.swing.text/DefaultFormatterFactory

Материал из Java эксперт
Перейти к: навигация, поиск

DefaultFormatterFactory: getDefaultFormatter()

 

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JFormattedTextField;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;
public class Main {
  public static void main(String[] argv) throws Exception {
    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"));
    //formatter.setFormat(new SimpleDateFormat("HH:00 a"));
  }
}





new DefaultFormatterFactory(AbstractFormatter d, AbstractFormatter di, AbstractFormatter e)

 
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;
public class MainClass {
  public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame("Formatted Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    DateFormat displayFormat = new SimpleDateFormat("yyyy--MMMM--dd");
    DateFormatter displayFormatter = new DateFormatter(displayFormat);
    DateFormat editFormat = new SimpleDateFormat("MM/dd/yy");
    DateFormatter editFormatter = new DateFormatter(editFormat);
    DefaultFormatterFactory factory = new DefaultFormatterFactory(displayFormatter,
        displayFormatter, editFormatter);
    JFormattedTextField date2TextField = new JFormattedTextField(factory, new Date());
    frame.add(date2TextField, BorderLayout.NORTH);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        JFormattedTextField source = (JFormattedTextField) actionEvent.getSource();
        Object value = source.getValue();
        System.out.println("Class: " + value.getClass());
        System.out.println("Value: " + value);
      }
    };
    date2TextField.addActionListener(actionListener);
    frame.add(new JTextField(), BorderLayout.SOUTH);
    frame.setSize(250, 100);
    frame.setVisible(true);
  }
}