繁体   English   中英

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

[英]How to set a default text to JFormattedTextField?

我的GUI程序中有以下JFormattedTextField。

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

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

你可以...

看看SwingLabs,SwingX库中可用的PromptSupport ...

提示

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提供输入提示

提示

你可以...

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

提示

三角洲,

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

快速入门指南足以助您一臂之力!

请让我知道,如果你有任何问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM