创建对话框时不兼容的类型错误

时间:2012-10-18 09:15:22

标签: java swing compiler-errors joptionpane

我正在尝试使用JOptionPane的静态方法创建输入对话框:

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

我的代码如下:

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

这让我错误:

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

一定有一些我想念的简单......

2 个答案:

答案 0 :(得分:2)

JOptionPane.showInputDialog()返回一个对象as specified in the doc,但你期待一个String。请注意选择选项

 Object[] selectionValues

Objects的数组,因此您将获得其中一个对象。没有什么可说的,他们被指定为字符串。如果值字符串,那么您可以/应该正确投射。

另请注意,您传递的是null数组。来自doc:

  

用户可以从selectionValues中进行选择,其中null表示   用户可以输入他们想要的任何内容

答案 1 :(得分:1)

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

也许这会解决它