Search code examples
javaswingjoptionpane

Can't display intiali value in JoptionPane within JDialog


This is probably a dumb question, but I can't figure out how to fix it. I want all my JoptionPanes to be resizable, so I am imbedding them in JDialog. I will have to convert all my showXxxDialog calls eventually, so I decided to start with showInputDialog. Everything works (the Dialog looks nice, and is resizable), except that it won't display the initial value in the JOptionPane display, even though it is correct in the JOptionPane constructor. Here is my code (messageType is PLAIN_MESSAGE, but QUESTION_MESSAGE does the same):

public class MyOptionPane {

static Object showInputDialog(Object f,  Object message, String title, int messageType, 
      Icon ico, Object[] options, Object initValue) {

     JOptionPane pane = new JOptionPane(message, messageType, JOptionPane.OK_CANCEL_OPTION,
         ico, options,  initValue);

     JDialog dialog = pane.createDialog((Component) f, title);
     if (!dialog.isResizable()) {
         dialog.setResizable(true);
     }
     pane.setWantsInput(true);

     dialog.pack();              
     dialog.setVisible(true);           

     return pane.getInputValue();   

     }
 }

Help would be much appreciated!


Solution

  • I have good and bad news, a fix to your problem is to include the line: pane.setInitialSelectionValue(initValue);. Great right? Well the bad news is that I cannot explain why it doesn't auto insert the initValue via the constructor. Hopefully someone else can build off of this and explain to us both.

    import javax.swing.*;
    import java.awt.*;
    
    public class MyOptionPane {
    
        static Object showInputDialog(Object f,  Object message, String title, int messageType,
                                      Icon ico, Object[] options, Object initValue) {
    
    
            JOptionPane pane = new JOptionPane(message, messageType, JOptionPane.OK_CANCEL_OPTION,
                    ico, options,  initValue);
    
            JDialog dialog = pane.createDialog((Component) f, title);
            if (!dialog.isResizable()) {
                dialog.setResizable(true);
            }
            pane.setInitialSelectionValue(pane.getInitialValue()); // set it
            pane.setWantsInput(true);
    
            dialog.pack();
            dialog.setVisible(true);
    
            return pane.getInputValue();
        }
    }