如何将默认文本设置为JFormattedTextField?

时间:2015-03-30 05:10:29

标签: java swing

我的GUI程序中有以下JFormattedTextField。

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

我想在字段中设置默认文本,以便用户知道以正确格式“dd / MM / yyyy”输入日期?我该怎么做?

2 个答案:

答案 0 :(得分:3)

你可以......

查看SwingLabs, SwingX library ...

中提供的PromptSupport

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);
            }
        });
    }

}

你可以......

使用字段旁边添加的JLabel来提供输入提示

Prompt

你可以......

使用工具提示文字支持DOB.setToolTipText("In dd/MM/yyyy format");

tooltip

答案 1 :(得分:1)

Delta,

您可以使用PromptSupport库的xswingx功能输入默认值。

快速入门指南足以让您前进!

如果您有任何疑问,请与我们联系。