[英]Is there a way to prevent a JFormattedTextField from automatically erasing invalid input?
我正在使用帶有MaskFormatter的JFormattedTextField來輸入電話號碼。
但是,當我輸入無效的電話號碼(例如“123”)然后按下按鈕時,JFormattedTextField會立即刪除所有文本。
有沒有辦法將無效文本保存在那里?
這是一個代碼示例:
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();
}
});
}
}
如果只輸入幾個數字,例如123,然后按下按鈕,您將看到它如何自動刪除所有文本。
似乎因為我指定了
maskFormatter.setPlaceholderCharacter('_');
它正在用下划線替換所有無效字符,雖然我想知道是否有辦法保留無效的123輸入,以及剩余的下划線。
直接從javadoc的第三行:
JFormattedTextField允許配置丟失焦點時應采取的操作。 可能的配置是[...]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.