首页 > 解决方案 > 我如何制作像 DateField 这样的 JtextField,其中永久添加了 Slash(/)

问题描述

我怎样才能制作一个包含永久可见斜线划分月、日和年值的JtextField类似内容。DateField如下例所示,当字段为空时,斜线可见,当用户输入值时,日期值将绕过斜线。也就是说,如果用户031618在字段中键入,它将显示为03/16/18

textField 看起来像这样

我在网上看到过这样的例子,所以我知道这是可能的,但我不知道如何让它自己工作。

标签: javaswing

解决方案


import java.awt.*;
import java.text.ParseException;
import javax.swing.*;
import javax.swing.text.MaskFormatter;

public final class MaskFormatterTest {
  private Component makeUI() {
    String mask = "##/##/##";
    JFormattedTextField field = new JFormattedTextField(createFormatter(mask));
    field.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
    field.setText("031618");

    JPanel p = new JPanel(new GridLayout(2, 1, 10, 10));
    p.add(field);
    p.add(new JTextField("03/16/18"));

    JPanel panel = new JPanel(new BorderLayout());
    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    panel.add(p, BorderLayout.NORTH);
    return panel;
  }
  protected static MaskFormatter createFormatter(String s) {
    MaskFormatter formatter = null;
    try {
      formatter = new MaskFormatter(s);
    } catch (ParseException ex) {
      System.err.println("formatter is bad: " + ex.getMessage());
    }
    return formatter;
  }
  public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new MaskFormatterTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}

推荐阅读