我正在制作一个 JOptionpane,用户必须在其中输入他的名字。所以不能为空也不能是数字
空部分可以工作,但现在我必须找到数字部分的解决方案
正如您在我的代码中看到的,我做了一个 while 循环来检查“naam”是否不为空。现在我需要找到一种方法来检查“naam”是否不是数字。
String naam = JOptionPane.showInputDialog("Geef uw naam in: ");
while (naam.equals("")) {
JOptionPane.showMessageDialog(null, "Geef een naam in", "Geef naam", JOptionPane.ERROR_MESSAGE);
naam = JOptionPane.showInputDialog("Geef uw naam in: ");
最佳答案
您可以直接在对话框中直接过滤输入,而不必费力地显示错误对话框并重新显示对话框...
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
甚至错误消息...
关于java - 输入只能是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15284062/