您可以简单地直接在对话框中过滤输入,而不是搞乱必须显示错误对话框并重新显示对话框......
import java.awt.EventQueue;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class TestOptionPane08 {
public static void main(String[] args) {
new TestOptionPane08();
}
public TestOptionPane08() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField name = new JTextField(10);
((AbstractDocument) name.getDocument()).setDocumentFilter(new DocumentFilter() {
public String filter(String text) {
StringBuilder sb = new StringBuilder(text.length());
for (char c : text.toCharArray()) {
if (!Character.isDigit(c)) {
sb.append(c);
}
}
return sb.toString();
}
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, filter(string), attr);
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
String filter = filter(text);
super.replace(fb, offset, length, filter, attrs);
}
});
JOptionPane.showMessageDialog(null, name, "Name Please", JOptionPane.QUESTION_MESSAGE);
}
});
}
}
现在,您可以添加JTextField
toJPanel
并添加 aJLabel
甚至错误消息...