Search code examples
javaswingjoptionpane

How JOptionPane's showInputDialog Works?


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?


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