I am very new to programming and I am totally lost on this homework assignment. The assignment is to have a gui that displays two different dice. When I click on the button the random number generator is supposed to have different images of the dice appear. I can get my images to appear when I don't have any "if" statements so I know that the path is working. When I add the "if" statements to assign the image for one of the dice I get an error that it cannot find symbol. Since this worked when the icon was statically assigned I assume it is the "if" statement causing the problem but it may come back to the random number. Please advise on what I am doing wrong. The code attached only has the non-working code for the left die.
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();
}
}
You are facing scope issues, leftDie
scope is restricted to if block only so, move the ImageIcon leftDie ==
out of your if
statements. Change this code:
if (valLeft==1)
{
ImageIcon leftDie = new ImageIcon("Die1.png");
}
To like this:
ImageIcon leftDie = null;
if (valLeft==1)
{
leftDie = new ImageIcon("Die1.png");
}
This should work.