【问题标题】:Custom icon JOptionPane.showInputDialog自定义图标 JOptionPane.showInputDialog
【发布时间】:2016-03-01 21:59:12
【问题描述】:

我正在尝试在 JOptionPane.showMessageDialog 上放置自定义图标,但出现错误

public static String input (String message)
{
    ImageIcon icon = new ImageIcon("alien.jpg");
    String text = message;
    return JOptionPane.showInputDialog(null,text,"Alien Pet Game",JOptionPane.INFORMATION_MESSAGE,icon,null,"");
}

这是我的错误:

error: incompatible types: Object cannot be converted to String return JOptionPane.showInputDialog(null,text,"Alien Pet Game",JOptionPane.INFORMATION_MESSAGE,icon,null,"");

我该怎么办?

【问题讨论】:

  • 你能解决这个问题吗?

标签: java swing icons


【解决方案1】:

您对图标的使用(可能)没有任何问题。该错误是指 showInputDialog 的返回值,它是一个对象,您正在调用一个字符串。您需要做的就是将返回值转换为 String:

return (String) JOptionPane.showInputDialog(null,text,"Alien Pet Game",JOptionPane.INFORMATION_MESSAGE,icon,null,"");

【讨论】:

    【解决方案2】:

    编辑:您可以选择将对象转换为字符串。

    1- 检查您的消息是否不为空并将返回语句转换为字符串。

    2- 你可以调用 toString()

    3-String.valueOf() - 你可以避免 toString() 的空异常问题。

    这里参考以上项目:(Java: JTable change listener, "Object cannot be converted to string" error

      return (String) JOptionPane.showInputDialog(null,text,"Alien Pet Game",JOptionPane.INFORMATION_MESSAGE,icon,null,"");    
    

    编辑方法:

       public static void main(String[] args) {
           input("Hi");
       }
    
    
       public static String input(String message){
    
            ImageIcon icon = new ImageIcon("alien.jpg");
            String text = message;
            if(text != null)
           return (String) JOptionPane.showInputDialog(null,text,"Alien Pet Game",JOptionPane.INFORMATION_MESSAGE,icon,null,"");
    
            /* else 
                return Alternative*/
                return null;
       }
    

    【讨论】:

      【解决方案3】:

      您的方法将字符串变量作为参数,并且您试图返回一个 JOptionPane 对象,只需将该对象存储在字符串变量中

      String s = JOptionPane.showInputDialog(message));
      

      并返回那个变量's'

      【讨论】:

        猜你喜欢
        • 2021-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-18
        • 2015-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多