8

I'm having trouble creating a fixed date format using JTextField. Is there a way for JTextField to have a fixed date format ?

james.garriss
  • 12,959
  • 7
  • 83
  • 96
Janpol Seda
  • 81
  • 1
  • 1
  • 3
  • 4
    Have a look at [JFormattedTextField](http://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.html). – Reimeus Sep 29 '12 at 19:35
  • 2
    Or use a more modern UI component like the [`JXDatePicker`](http://www.javalobby.org/java/forums/t45447.html) – Robin Sep 29 '12 at 21:38

7 Answers7

10

You can use JFormattedTextField with SimpleDateFormat

DateFormat format = new SimpleDateFormat("your_format");
JFormattedTextField dateTextField = new JFormattedTextField(format);
joval
  • 466
  • 1
  • 6
  • 15
3

You should take a look at

For starters...

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

If you're using Swing, add a JFormattedTextField to your JFrame. In the Properties, click on formatterFactory. In the dialog, choose the Date Category and then select a Format. Now your format will be enforced.

enter image description here

james.garriss
  • 12,959
  • 7
  • 83
  • 96
0

my solution in Netbeans is : select the date from JDateChooser component ,then one unfocusable jtextfield get the date from the selected date in JDateChooser: (1)in order to make fixed date format, in the properties of JDateChooser ,for example we set the date format :yyyy-MM-dd ; (2)make "jtextfield.setFocusable(false)", this is for avoiding input wrong date format or unwanted characters

enter image description here

enter image description here

enter image description here enter image description here

0

As has been said in the comments, you may prefer to look into a date picker component instead of a text field. A date picker component will save the user from struggling with date syntax.

java.time

I recommend that you use java.time, the modern Java date and time API, for your date work. So for anyone preferring a text field for a date, I did a small experiment with using a JFormattedTextField in conjunction with the LocalDate class from java.time. For the text field I found it nicest to write a little subclass specifying that the type of object we get from a date field is LocalDate:

public class DateField extends JFormattedTextField {

    private static final long serialVersionUID = -4070878851012651987L;

    public DateField(DateTimeFormatter dateFormatter) {
        super(dateFormatter.toFormat(LocalDate::from));
        setPreferredSize(new Dimension(100, 26));
    }

    @Override
    public LocalDate getValue() {
        return (LocalDate) super.getValue();
    }

}

A JFormattedTextField accepts a java.text.Format object for formatting and parsing values. DateTimeFormatter from java.time has a couple of overloaded toFormat methods that give us java.text.Format. Even one where we can specify the type of object we get from the Format.

To try this date field class out:

public class TestFrame extends JFrame {

    public TestFrame() {
        super("Test");
        setLayout(new FlowLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
                .withLocale(Locale.forLanguageTag("es"));
        DateField dateField = new DateField(dateFormatter);
        add(dateField);
        dateField.setValue(LocalDate.now(ZoneId.systemDefault()));

        JButton okButton = new JButton("OK");
        okButton.addActionListener(ev -> JOptionPane.showMessageDialog(TestFrame.this,
                "Date entered is " + dateField.getValue()));
        add(okButton );

        pack();
    }

    public static void main(String[] args) {
        new TestFrame().setVisible(true);
    }

}

I specified Spanish format just to demonstrate clearly that formatting and parsing is going on. This is where you can specify yourself which format your users prefer. For example DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT) or DateTimeFormatter.ofPattern("dd/MM/uu"). Consider a short format since most users don’t like typing more than necessary.

Now the JFrame came up looking like this:

enter image description here

Instead of today’s date I entered 11 ago. 2020 and clicked OK:

enter image description here

Link

Oracle tutorial: Date Time explaining how to use java.time.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

Use property formatterFactory and select format.like this

-2

I think the best is using the JFormatedTextField.

I have this code try this one:

package your_package;

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

public class.....{

private String getdate(){
      DateFormat format = new SimpleDateFormat("MM/DD/YYYY"); //display your format.
      Date date = new Date();//puts the date in variable.
      return dateformat.format(date); //returns the format to the date variable.
}

public your_app{
     .....
     String date = new getdate();
     txtDate.setvalue(date);
}
}

Hope this will give you an idea and helps... :)

  • 4
    well ... there are some issues with your answer: the code snippet a) doesn't relate to your description b) it won't compile (even with thinking the dots as full-fledged code :-) c) doesn't comply with java naming conventions d) the logic is upside-down (assuming txtData is the formattedTextField) e) nothing new compared to the other answers ... – kleopatra Jun 17 '13 at 09:00