java - 我如何制作像 DateField 这样的 JtextField,其中永久添加了 Slash(/)
问题描述
我怎样才能制作一个包含永久可见斜线划分月、日和年值的JtextField
类似内容。DateField
如下例所示,当字段为空时,斜线可见,当用户输入值时,日期值将绕过斜线。也就是说,如果用户031618
在字段中键入,它将显示为03/16/18
:
我在网上看到过这样的例子,所以我知道这是可能的,但我不知道如何让它自己工作。
解决方案
- 您可以使用MaskFormatter:
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);
});
}
}
推荐阅读
- javascript - 在 IE 中直接使用 Polyfill ES5
- visual-c++ - 二次方程的c++实现,在学校测试网站上实现时抛出错误
- laravel - 为用户类变量赋值
- rest - REST API 关系中的公共 ID
- java - 需要找到属性并点击它
- javascript - 如何一次定义很多变量
- ruby-on-rails - systemd脚本中的`bundle:找不到命令`
- django - 编辑更新除 Django Rest Framework 中的主键之外的所有计划
- c++ - 警告 C4267“正在初始化”:从“size_t”转换为“DWORD”,可能丢失数据
- java - 使用 JSP 动态创建 JNLP 文件时,Eclipse 中出现未知标记 jnlp 警告