Tuesday, August 10, 2010

Setting Initial value for InputDialog in JOptionPane

There are 6 showInputDialog methods in JOptionPane class and we can select either one of these methods based on our requirements. To create an initial value when an InputDialog pops out we need to make use of method with these signatures:
public static Object showInputDialog(Component parentComponent,
Object message,
String title,
int messageType,
Icon icon,
Object[] selectionValues,
Object initialSelectionValue)
throws HeadlessException
Let me describe the parameters in a more understandable way compared to the ones in the Java API Doc.
  • parentComponent - the parent Component for the dialog
  • message – The message to display when the dialog pops out
  • title – The title of the dialog
  • messageType - the type of message to be displayed: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE
  • icon – Your very own icon for the dialog
  • selectionValues – Provide few values to select (If this is null, the input field will be a JTextField rather than a JComboBox)
  • initialSelectionValue – The default initial value for the dialog


If you look at the code above, I made the parentComponent as null because the dialog is not referring to any component and I’ve declared the icon null as well because I don’t need a customized icon.

When I declare the selectionValues with an array called values, the input field turns into a JComboBox and the default value is assigned based on the initialSelectionValue, in this case its "A".

Let's say I don't want to provide options to the users and expect them to key in the values manually, but I still want to provide an initial value. All I have to do for that is, make the selectionValues parameter as null.


For further reference, have a look at the javadoc for JOptionPane: JOptionPane

Author: Thiagu

No comments:

Post a Comment