【问题标题】:Getting a different image to appear in a gui based on a random number generator基于随机数生成器在 gui 中显示不同的图像
【发布时间】:2014-03-20 03:43:58
【问题描述】:

我对编程很陌生,我完全迷失在这个家庭作业中。任务是要有一个显示两个不同骰子的 gui。当我单击按钮时,随机数生成器应该会出现不同的骰子图像。当我没有任何“if”语句时,我可以让我的图像出现,这样我就知道路径正在运行。当我添加“if”语句为其中一个骰子分配图像时,我得到一个错误,它找不到符号。由于这在静态分配图标时有效,我认为它是导致问题的“if”语句,但它可能会回到随机数。请告知我做错了什么。附上的代码只有左模具的无效代码。

private class ButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {

        Random randomNumbers = new Random();  // Generates random numbers
        int valLeft;  // holds random number
        int valRight;  // holds random number

        // get values for the dice
        valLeft = randomNumbers.nextInt(6)+1; // range 1-6
        valRight = randomNumbers.nextInt(6)+1; // range 1-6

        // assign the image for the left die
        if (valLeft==1)
        {
            ImageIcon leftDie = new ImageIcon("Die1.png");
        }
         if (valLeft==2)
        {
            ImageIcon leftDie = new ImageIcon("Die2.png");
        }
          if (valLeft==3)
        {
            ImageIcon leftDie = new ImageIcon("Die3.png");
        }
           if (valLeft==4)
        {
            ImageIcon leftDie = new ImageIcon("Die4.png");
        }
            if (valLeft==5)
        {
            ImageIcon leftDie = new ImageIcon("Die5.png");
        }
             if (valLeft==6)
        {
            ImageIcon leftDie = new ImageIcon("Die6.png");
        }


        // put image on label
        imageLabelLeft.setIcon(leftDie);

        // assign the image for the right die
        ImageIcon rightDie = new ImageIcon("Die6.png");
        imageLabelRight.setIcon(rightDie);

        // remove the text from the labels
        imageLabelLeft.setText(null);
        imageLabelRight.setText(null);

        // repack the frame for the new images
        pack();

    }
}

【问题讨论】:

    标签: java user-interface imageicon actionevent


    【解决方案1】:

    您正面临范围问题,leftDie 范围仅限于 if 阻止,因此请将 ImageIcon leftDie == 从您的 if 语句中移出。更改此代码:

        if (valLeft==1)
        {
            ImageIcon leftDie = new ImageIcon("Die1.png");
        }
    

    喜欢这样:

        ImageIcon leftDie = null;
        if (valLeft==1)
        {
            leftDie = new ImageIcon("Die1.png");
        }
    

    这应该可行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 2015-12-09
      • 1970-01-01
      相关资源
      最近更新 更多