【问题标题】:Presenting random pictures using JOptionPane icon and Math.random使用 JOptionPane 图标和 Math.random 呈现随机图片
【发布时间】:2013-03-13 17:34:42
【问题描述】:

我正在上编程课,我必须让乐器“演奏”。我想使用 Math.random 创建一个介于 0-9 或 0-10 之间的随机数,并让该数字对应于通过 JOptionPane 图标显示的数组中的图片。我唯一的问题是,如何创建一个将随机 int 对应于图片的程序,然后使用 JOption Pane 呈现它。这是我目前所拥有的:

   public static String Flute(String pickYourInstrument, String instrument){
      //try to assign variables to pictures in an array
      ImageIcon icon = new ImageIcon("/home/james/programmingpics/A_Flute");
      JOptionPane.showMessageDialog(null, "A Note", "A Note with Flute", 
      JOptionPane.OK_OPTION, icon);
      for (int i = 0; i < 1000; i++) {
           int random = 1 * (int) (Math.random() * 10);
           System.out.println(random);
      }
   }

我被卡住了,在我意识到我不知道如何将 ImageIcon 图标制作成一个数组后我停下来(我还有九张其他图片要制作一个图标)。有谁知道我如何创建这个程序?

【问题讨论】:

    标签: java arrays swing joptionpane imageicon


    【解决方案1】:

    只需创建一个ImageIcon数组,然后得到的随机数就可以作为该数组的索引,得到对应的图标。像

    这样简单的东西
    int randomNumber = //.... get random int
    ImageIcon myIcon = iconArray[randomNumber];
    

    【讨论】:

    • 做到了,谢谢。关于如何让它以 500 毫秒滚动而不是提示 ok 的任何想法?
    • @trashgod:是的,这也行得通,尤其是当需要以非重复方式获取随机图标时。
    猜你喜欢
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 2020-12-24
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2022-10-22
    相关资源
    最近更新 更多