2

我尝试通过以下方式从用户那里获得输入:

int myNumber = Integer.parseInt((String) JOptionPane.showInputDialog(
                            frame,
                            "Number you want:\n",
                            "Enter number",
                            JOptionPane.PLAIN_MESSAGE,
                            null,
                            null,
                            "5"));

它运作良好,但我不确定用户是否会在该字段中输入一个数字,我不想NumberFormatException被抛出。

有没有办法将 a 设置formatter为(就像我们可以设置JOptionPanea 的文本字段一样)?JFormattedTextFieldDecimalFormat

4

3 回答 3

2

简短的回答:不,没有办法做到这一点。JOptionPane 不提供在关闭之前验证其输入的任何方法。

解决此问题的一种简单方法是使用 JSpinner。JOptionPane 允许将组件和数组用作消息对象,因此您可以执行以下操作:

int min = 1;
int max = 10;
int initial = 5;

JSpinner inputField =
    new JSpinner(new SpinnerNumberModel(initial, min, max, 1));

int response = JOptionPane.showOptionDialog(frame,
    new Object[] { "Number you want:\n", inputField },
    "Enter number",
    JOptionPane.OK_CANCEL_OPTION,
    JOptionPane.PLAIN_MESSAGE,
    null, null, null);

if (response == JOptionPane.OK_OPTION) {
    int myNumber = (Integer) inputField.getValue();
    // Do stuff with myNumber here
} else {
    System.out.println("User canceled dialog.");
}

您还可以按照您的建议将 JFormattedTextField 作为消息对象而不是 JSpinner 传递。

于 2013-05-14T18:28:32.367 回答
1

有关编辑值的方法,请参阅有关停止自动对话框关闭的 Swing 教程。

或者查看 JOptionPane API。也许使用:

showConfirmDialog(Component parentComponent, Object message, String title, int optionType) 

消息可以是一个 Swing 组件。

于 2013-05-14T18:26:04.217 回答
1

将您想要的 JFormattedTextField 提供给您的对话框怎么样?

    JFormattedTextField field = new JFormattedTextField(DecimalFormat.getInstance());
    JOptionPane.showMessageDialog(null, field);
    System.out.println(field.getText());

如果它更适合您,您还可以使用更精细的组件。

于 2013-05-14T19:11:48.487 回答