创建要求编号的对话框的最佳方法是什么?并避免用户可以输入字母或将对话框留空的情况? 我写了这样的东西,但我认为它可以改进:
private int giveInt(String message)
{
int result =0;
boolean successful = false;
String[] options = {"OK"};
JPanel panel = new JPanel();
JLabel lbl = new JLabel(message);
JTextField txt = new JTextField(10);
panel.add(lbl);
panel.add(txt);
do{
try {
int selectedOption = JOptionPane.showOptionDialog(null, panel,
"Enter number", JOptionPane.NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options , options[0]);
if(selectedOption == 0)
{
String input= txt.getText();
if(input!=null)
{
result = Integer.parseInt(input);
successful = true;
}
else result=0;
}
} catch (InputMismatchException ime) {
JOptionPane.showMessageDialog(null, "Please enter an number");
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Please enter an number");
}
}while (!successful);
return result;
}