【问题标题】:How to set a default text to JFormattedTextField?如何将默认文本设置为 JFormattedTextField?
【发布时间】:2015-03-30 05:10:28
【问题描述】:

我的 GUI 程序中有以下 JFormattedTextField。

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

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

【问题讨论】:

  • 查看 SwingLabs、SwingX 库中的PromptSupport,用于example

标签: java swing


【解决方案1】:

你可以...

看看SwingLabs, SwingX library中的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");

【讨论】:

  • 非常彻底的回答,干得好。 +1
  • 是的,就是我,越过顶部:P
  • 我非常感谢你...JLabel 方法可以满足我的目的,但我希望在我成为更好的程序员时使用 PromptSupport...谢谢
  • 很高兴(全部)能帮上忙;)
【解决方案2】:

三角洲,

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

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

如果您有任何问题,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    相关资源
    最近更新 更多