Question

I was wondering how inputdialog returns value especially when there are also ok and cancel buttons. Could somebody explain how does it manage to return value?

UPDATE:

Let me put it this way. I want to create a dialog with 6 buttons and each button returns different value. And i want it get that value like this: String value = MyDialog.getValue(); // like showInputDialog

the problem is how do i return value on button press?

Was it helpful?

Solution

Now that I have a clearer understanding of your goal, I think instead of trying to emulate JOptionPane, it would be easier to just give each button a different 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();
    }
}

OTHER TIPS

From the Java tutorials

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;
}

You might like to familiarise yourself with the section on "Getting the User's Input from a Dialog"

You should also familiarise yourself with the Java Docs on the same subject

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top