Search code examples
javaswingjoptionpane

JOptionPane.showOptionDialog shows no buttons?


The following code shows a dialog as expected, apart from having no buttons:

  final JPasswordField passwdField = new JPasswordField();
  passwdField.setColumns(20);
  final JComponent[] inputs = new JComponent[] {  passwdField };
  int res = JOptionPane.showOptionDialog(null, "Enter Password", "Login", 
                  JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, 
                  null, inputs, "");

shows the following dialog (Java 6.2?, Windows 7 64-Bit):

enter image description here

Why are there no OK / Cancel button? (btw, the dialog is not resizable, so I don't know if they are just outside the visible frame)

(Also, pressing Enter does not close the dialog, "x" closes the dialog)


Solution

  • Your problem is with the inputs array. Read the API and it will tell you that it should be different. I usually use an array of String, each String representing a button String, or sometimes I use a mixture of Objects, mixing components and Strings. For e.g.,

      JPasswordField passField = new JPasswordField(10);
      Object[] inputs = {passField, "OK", "Cancel"};
      int res = JOptionPane.showOptionDialog(null, "Enter Password", "Login", 
               JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, 
               null, inputs, "");
      if (res == 1) {
         System.out.println("Password is: " + new String(passField.getPassword()));
      }