如何将默认文本设置为 JFormattedTextField? [英] How to set a default text to JFormattedTextField?

查看:31
本文介绍了如何将默认文本设置为 JFormattedTextField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 GUI 程序中有以下 JFormattedTextField.

I have the following JFormattedTextField in my GUI program.

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

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

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?

推荐答案

你可以...

查看 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");

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

这篇关于如何将默认文本设置为 JFormattedTextField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆