【问题标题】:How to set an ImageIcon using a Switch statement如何使用 Switch 语句设置 ImageIcon
【发布时间】:2015-03-28 15:24:17
【问题描述】:

好吧,我在编码方面几乎是全新的,但我正在努力。

我需要创建一个 ImageIcon,它将使用 switch 语句来确定要显示的图像。

我看了这里的帖子:Change image with if statement

它建议使用 switch 语句而不是 if 语句,所以我认为它会有所帮助。但是,当我编辑我的代码并从以前的代码中更改它时,我收到一条错误消息,提示“无法将 ImageIcon 解析为变量”。我尝试了各种大写组合,但没有一个有效。我将最初拥有的代码留在了第一种情况下。该代码没有给我任何错误消息,但我认为我不应该为每种情况创建一个新的 ImageIcon,因为我需要从程序中的一个中提取并让 switch 语句确定要显示的图像。

修改后的代码

  public ImageIcon dieImage(String string)
   {
       ImageIcon dieImage = new ImageIcon("");

      switch (faceValue){

       case 1: dieImage = new ImageIcon ("src/1.jpg");
       break;
       case 2: dieImage = new ImageIcon("src/2.jpg");
       break;
       case 3: dieImage = new ImageIcon("src/3.jpg");
       break;
       case 4: dieImage = new ImageIcon("src/4.jpg");
       break;
       case 5: dieImage = new ImageIcon("src/5.jpg");
       break;
       case 6: dieImage = new ImageIcon("src/6.jpg");
       break; 
      }
    return dieImage;
   }
}

任何帮助将不胜感激。

【问题讨论】:

    标签: java eclipse image switch-statement


    【解决方案1】:
    {
       ImageIcon icon = new ImageIcon("");
    }
    

    去掉 {} 并使用:

    ImageIcon icon;
    

    现在您的 switch 语句可以分配正确的图标以供您的标签使用。

    //case 1: ImageIcon = ("src/1.jpg");
    case 1: icon = new ImageIcon("src/1.jpg");
    

    您的语法无效,如上所示修复代码。

    您的其他语句也不做任何事情,因为它们只是创建了一个图标,但图标没有分配给可以使用的变量。代码应该是:

    //case 2: new ImageIcon("src/2.jpg");
    case 2: icon = new ImageIcon("src/2.jpg");
    

    然后要使用此图标,您需要更新包含该图标的标签:

    label.setIcon( icon );
    

    【讨论】:

    • 那么,我必须为每个案例都有一个“新”图像图标吗?这是包含您的建议和 Eclipse 希望我做出的更改的更新代码。现在没有错误,但我不确定返回应该是“dieImage”还是“null”。
    • 感谢您的帮助!
    • @Rachel,是的,您返回图标。不要忘记“接受”答案,这样人们就知道问题已经解决了。
    • 感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多