JOptionPane /输入对话框

时间:2013-05-14 18:00:56

标签: java swing joptionpane

我尝试用这个来获取用户的输入:

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

它运作良好,但我不确定用户是否会在字段中输入数字,我不希望抛出NumberFormatException

有没有办法将formatter设置为JOptionPane(就像JFormattedTextField设置为DecimalFormat的文字字段一样?)

3 个答案:

答案 0 :(得分: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传递。

答案 1 :(得分:1)

请参阅Stopping Automatic Dialog Closing上的Swing教程,了解编辑值的方法。

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

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

消息可以是Swing组件。

答案 2 :(得分:1)

如果要将JFormattedTextField提供给对话框呢?

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

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