0

我想知道 inputdialog 如何返回值,尤其是当还有 ok 和 cancel 按钮时。有人可以解释它是如何返回值的吗?

更新:

让我这样说吧。我想创建一个包含 6 个按钮的对话框,每个按钮返回不同的值。我希望它得到这样的值: String value = MyDialog.getValue(); // 像 showInputDialog

问题是我如何在按钮按下时返回值?

4

2 回答 2

2

来自Java 教程

Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
    frame,
    "Complete the sentence:\n"
    + "\"Green eggs and...\"",
    "Customized Dialog",
    JOptionPane.PLAIN_MESSAGE,
    icon,
    possibilities,
    "ham");

//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
    setLabel("Green eggs and... " + s + "!");
    return;
}

您可能想熟悉“从对话框中获取用户输入”部分

您还应该熟悉有关同一主题的Java 文档

于 2013-01-25T00:44:29.417 回答
2

现在我对您的目标有了更清晰的了解,我认为与其尝试模拟 JOptionPane,不如为每个按钮提供不同的 actionCommand:

private JDialog dialog;

private String inputValue;

String showPromptDialog(Frame parent) {
    dialog = new JDialog(parent, true);
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    // [add components to dialog here]

    firstButton.setAction(new ButtonAction("Button 1",  "first"));
    secondButton.setAction(new ButtonAction("Button 2", "second"));
    thirdButton.setAction(new ButtonAction("Button 3",  "third"));
    fourthButton.setAction(new ButtonAction("Button 4", "fourth"));
    fifthButton.setAction(new ButtonAction("Button 5",  "fifth"));
    sixthButton.setAction(new ButtonAction("Button 6",  "sixth"));

    dialog.pack();
    dialog.setLocationRelativeTo(parent);

    inputValue = null;
    dialog.setVisible(true);

    return inputValue;
}

private class ButtonAction
extends AbstractAction {
    private static final long serialVersionUID = 1;

    ButtonAction(String text,
                 String actionCommand) {
        super(text);
        putValue(ACTION_COMMAND_KEY, actionCommand);
    }

    public void actionPerformed(ActionEvent event) {
        inputValue = event.getActionCommand();
        dialog.dispose();
    }
}
于 2013-01-25T12:37:07.027 回答