エラーダイアログを表示したり、ダイアログを再表示したりする必要はなく、ダイアログで直接入力をフィルタリングするだけで済みます...
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
したりすることができます...JPanel
JLabel