[英]Is there a way to prevent a JFormattedTextField from automatically erasing invalid input?
I am using a JFormattedTextField with a MaskFormatter applied to it in order to input a phone number. 我正在使用带有MaskFormatter的JFormattedTextField来输入电话号码。
However, when I enter an invalid phone number, such as "123" and then press a button, the JFormattedTextField immediately erases all of the text. 但是,当我输入无效的电话号码(例如“123”)然后按下按钮时,JFormattedTextField会立即删除所有文本。
Is there a way to keep that invalid text in there? 有没有办法将无效文本保存在那里?
Here is a code example: 这是一个代码示例:
import java.awt.FlowLayout;
import java.text.ParseException;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.text.MaskFormatter;
public class Example extends JFrame
{
private JFormattedTextField formattedTextField;
public Example()
{
this.getContentPane().setLayout(new FlowLayout());
try
{
MaskFormatter maskFormatter = new MaskFormatter("(###) ###-####");
maskFormatter.setPlaceholderCharacter('_');
formattedTextField = new JFormattedTextField(maskFormatter);
}
catch (ParseException pe)
{
System.out.println("Parse Exception");
}
JButton button = new JButton("OK");
add(formattedTextField);
add(button);
}
private static void createAndShowGUI()
{
JFrame frame = new Example();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
If you enter only a few digits, such as 123, and then press the button, you will see how it automatically deletes all of the text. 如果只输入几个数字,例如123,然后按下按钮,您将看到它如何自动删除所有文本。
It seems as though because I specify 似乎因为我指定了
maskFormatter.setPlaceholderCharacter('_');
it is replacing all of the invalid characters with the underscore, although I would like to know if there were a way to retain both the invalid 123 input, and also the remaining underscores. 它正在用下划线替换所有无效字符,虽然我想知道是否有办法保留无效的123输入,以及剩余的下划线。
Straight from the third line of the javadoc : 直接从javadoc的第三行:
JFormattedTextField allows configuring what action should be taken when focus is lost. JFormattedTextField允许配置丢失焦点时应采取的操作。 The possible configurations are [...] 可能的配置是[...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.