Dean
Dean

Reputation: 9118

Incompatible types error when creating dialog

I'm trying to create an input dialog, using a static method of JOptionPane:

public static Object showInputDialog(Component parentComponent,
                                     Object message,
                                     String title,
                                     int messageType,
                                     Icon icon,
                                     Object[] selectionValues,
                                     Object initialSelectionValue)
                              throws HeadlessException

My code is as follows:

String username = JOptionPane.showInputDialog(null, 
                                              "Username", 
                                              "Pick a name",    
                                              JOptionPane.PLAIN_MESSAGE,
                                              null, 
                                              null, 
                                              "default_name");

This gets me the error:

ChatController.java:49: incompatible types
found   : java.lang.Object
required: java.lang.String

There must be something simple I'm missing...

Upvotes: 0

Views: 696

Answers (2)

Brian Agnew
Brian Agnew

Reputation: 272287

JOptionPane.showInputDialog() returns an object, as specified in the doc, but you're expecting a String. Note that the selection options

 Object[] selectionValues

is an array of Objects, so you'll get one of those objects back. There's nothing to say they're specified as strings. If the values are strings, then you can/should cast appropriately.

Note also you're passing a null array. From the doc:

The user will able to choose from selectionValues, where null implies the user can input whatever they wish

Upvotes: 2

Bhavik Shah
Bhavik Shah

Reputation: 5183

String username =(String) JOptionPane.showInputDialog(null, 
                                          "Username", 
                                          "Pick a name",    
                                          JOptionPane.PLAIN_MESSAGE,
                                          null, 
                                          null, 
                                          "default_name");

maybe this will solve it

Upvotes: 1

Related Questions