Creating a Text Field to Display and Edit a Date - Java Swing

Java examples for Swing:JFormattedTextField

Description

Creating a Text Field to Display and Edit a Date

Demo Code

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JFormattedTextField;
import javax.swing.text.DateFormatter;

public class Main {
  public static void main(String[] args) {
    JFormattedTextField tft1 = new JFormattedTextField(new Date());

    JFormattedTextField tft2 = new JFormattedTextField(
        DateFormat.getDateInstance(DateFormat.SHORT));
    tft2.setValue(new Date());

    JFormattedTextField tft3 = new JFormattedTextField(new SimpleDateFormat(
        "yyyy-M-d"));
    tft3.setValue(new Date());

    Date date = (Date) tft3.getValue();

    DateFormatter fmt = (DateFormatter) tft3.getFormatter();
    fmt.setFormat(new SimpleDateFormat("d/M/yyyy"));

    tft3.setValue(tft3.getValue());//  ww w .  j  a v  a 2s  . co m
  }
}

Related Tutorials