我正在使用用 MaskFormatter 屏蔽的 JFormattedTextField 创建一个框架:
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("dd-mm-yyyy");
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.setLayout(new BorderLayout());
JFormattedTextField tf = new JFormattedTextField(df);
tf.setColumns(20);
panel.add(tf);
try {
MaskFormatter dateMask = new MaskFormatter("##-##-####");
dateMask.install(tf);
} catch (ParseException ex) {
Logger.getLogger(MaskFormatterTest.class.getName()).log(Level.SEVERE, null, ex);
}
frame.add(new JButton(), BorderLayout.LINE_START);
frame.add(panel, BorderLayout.LINE_END);
frame.pack();
frame.setVisible(true);
}
好的。没关系,但是当我删除(使用键盘键)我在字段中写的文本时,也会删除斜杠。有什么方法可以防止吗?我想删除文本但不删除斜线,例如:
写作日期:
"12-12-1212"
删除后:
" - - "
最佳答案
如何删除文本?你在使用 setText("")
吗?你不应该那样做。请改用 setValue(null)
。
如果那不是你的问题,请详细说明你在做什么,以及正在发生什么。
编辑:尝试这段代码,看看问题是否仍然存在。
public class Tester {
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.setLayout(new BorderLayout());
JFormattedTextField tf = new JFormattedTextField(df);
tf.setFocusLostBehavior(JFormattedTextField.COMMIT);
tf.setColumns(20);
panel.add(tf);
try {
MaskFormatter dateMask = new MaskFormatter("##-##-####");
dateMask.install(tf);
} catch (ParseException ex) {
}
frame.add(new JButton(), BorderLayout.LINE_START);
frame.add(panel, BorderLayout.LINE_END);
frame.pack();
frame.setVisible(true);
}
}´
编辑2: 尝试添加 tf.setFocusLostBehavior(JFormattedTextField.COMMIT); 查看 JavDoc进一步阅读。
关于java - Masked JFormattedTextField 防止删除斜杠字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21069864/