首页 > 解决方案 > 据我所知,showinputdialog 返回字符串类型的输出,但它给了我一个错误,它无法将对象转换为字符串

问题描述

 String val = JOptionPane.showInputDialog(null,
            "Search item to Edit ",
            "Warning",
            JOptionPane.QUESTION_MESSAGE,
            null,
            new String[]{"Item name", "Item no.","Price"},
            "");

错误:

不兼容的类型:对象不能转换为字符串

标签: java

解决方案


有了这么多参数,该方法showInputDialog不会返回一个字符串,而是一个对象,如javadoc中所述

正如Swing 教程中所建议的,您只需将结果转换为字符串。

String val = (String) JOptionPane.showInputDialog(null,
        "Search item to Edit ",
        "Warning",
        JOptionPane.QUESTION_MESSAGE,
        null,
        new String[]{"Item name", "Item no.","Price"},
        "");

推荐阅读