繁体   English   中英

JOptionPane的showInputDialog如何工作?

[英]How JOptionPane's showInputDialog Works?

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

更新:

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

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

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文档

现在,我对您的目标有了更清晰的了解,我认为与其尝试模仿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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM