0

I have the following JFormattedTextField in my GUI program.

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
JFormattedTextField DOB = new JFormattedTextField(df);

I want to set a default text to the field so that the user will know to input date in the correct format "dd/MM/yyyy"? How do I do that?

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Charlie
  • 3,113
  • 3
  • 38
  • 60
  • 1
    Take a look at the `PromptSupport` available in the SwingLabs, SwingX library, for [example](http://stackoverflow.com/questions/22807407/force-jtextfield-to-string-value-while-documentfilter-only-allows-digits/22827937#22827937) – MadProgrammer Mar 30 '15 at 05:11

2 Answers2

3

You could...

Take a look at the PromptSupport available in the SwingLabs, SwingX library...

Prompt

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jdesktop.swingx.prompt.PromptSupport;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                JFormattedTextField DOB = new JFormattedTextField(df);
                DOB.setColumns(10);

                PromptSupport.setPrompt("dd/MM/yyyy", DOB);
                PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.SHOW_PROMPT, DOB);

                JFrame frame = new JFrame("Testing");
                frame.setLayout(new GridBagLayout());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(DOB);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

You could...

Use a JLabel added next to the field to provide entry hints

Prompt

You could...

Use the tooltip text support, DOB.setToolTipText("In dd/MM/yyyy format");

tooltip

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

Delta,

You can input a default value using the PromptSupport functionality of the xswingx library.

The quick start guide is sufficient to get you going!

Please let me know if you have any questions.

Devarsh Desai
  • 5,984
  • 3
  • 19
  • 21