长答案是,使用DocumentFilter,有关详细信息,请参阅Implementing a Document Filter 和DocumentFilter Examples。
这样做的问题是,你需要控制,你不能依赖JOptionPane.showInputDialog提供的“简单”、“帮助”功能,因为你需要访问用于提示用户的文本字段...
例如...
以下示例使用来自DocumentFilter Examples 的PatternFilter 的(略微)修改版本
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;
public class ValidateTest {
public static void main(String[] args) {
JTextField field = new JTextField(20);
Pattern p = Pattern.compile("[0-9]+");
((AbstractDocument) field.getDocument()).setDocumentFilter(new PatternFilter(p));
int option = ask("Enter number:", field);
if (option == JOptionPane.OK_OPTION) {
System.out.println("You have entered " + field.getText());
}
}
public static int ask(String label, JComponent comp) {
JPanel panel = new JPanel();
panel.add(new JLabel(label));
panel.add(comp);
return JOptionPane.showOptionDialog(null, panel, label,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
}
public static class PatternFilter extends DocumentFilter {
// Useful for every kind of input validation !
// this is the insert pattern
// The pattern must contain all subpatterns so we can enter characters into a text component !
private Pattern pattern;
public PatternFilter(Pattern p) {
pattern = p;
}
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
throws BadLocationException {
String newStr = fb.getDocument().getText(0, fb.getDocument().getLength()) + string;
Matcher m = pattern.matcher(newStr);
if (m.matches()) {
super.insertString(fb, offset, string, attr);
} else {
}
}
public void replace(FilterBypass fb, int offset,
int length, String string, AttributeSet attr) throws
BadLocationException {
if (length > 0) {
fb.remove(offset, length);
}
insertString(fb, offset, string, attr);
}
}
}
现在,通过一点巧妙的设计,您可以编写一个简单的帮助类,它在内部构建所有这些,并提供了一个很好的 askFor(String label, Pattern p) 样式方法,可以返回 String(如果用户取消操作,则返回 null )