做一件事:
将默认文档存储在某个位置
final JTextField textField = new JTextField();
final Document defaultDocument=textField.getDocument();
单击按钮时首先将文档设置回默认值以禁用文本字段上的验证,然后设置默认文本
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textField.setDocument(defaultDocument);
textField.setText("hi");
}
});
将您的文档过滤器重新添加回文本字段中的焦点以验证用户输入。
请查看How to implement in Java ( JTextField class ) to allow entering only digits?。
-- 编辑--
您可以通过在text field 上添加focus listener 来实现。
如果文本字段中的值为空,则将默认值设置回作为提示。单击按钮时无需执行此操作。
代码如下:
final JTextField textField = new JTextField("First Name");
final Document defaultDocument = textField.getDocument();
final PlainDocument doc = new PlainDocument();
doc.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int off, String str, AttributeSet attr)
throws BadLocationException {
fb.insertString(off, str.replaceAll("\\D++", ""), attr); // remove
// non-digits
}
@Override
public void replace(FilterBypass fb, int off, int len, String str,
AttributeSet attr) throws BadLocationException {
fb.replace(off, len, str.replaceAll("\\D++", ""), attr); // remove
// non-digits
}
});
textField.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
System.out.println("focus lost");
if(textField.getText() == null || textField.getText().trim().length()==0){
textField.setDocument(defaultDocument);
textField.setText("First Name");
}
}
@Override
public void focusGained(FocusEvent e) {
System.out.println("focus gained");
textField.setDocument(doc);
}
});