I need a little help getting the syntax correct for calling a method. A class called "Die" has a method called getImage(). Its job is to construct a JLabel and in doing so it's supposed to call getDie1Image() within a class called "PairOfDice."
The job of getDie1Image() is to select one of six die face images and return it when called. Currently, I am getting an error message: "The method getDie1Image() is undefined for the type Die."
Yes, this is school work so I only should ask for help on this point only. Thanks.
Here is the segment from Die.java
public static void getImage()
{
JLabel face1, face2;
face1 = new JLabel(" ", getDie1Image(), SwingConstants.CENTER);
face2 = new JLabel(" ", getDie2Image(), SwingConstants.CENTER);
}
Here is the segment from PairOfDice.java
public ImageIcon getDie1Image()
{
int cube = die1.roll(); // returns int value 1-6
ImageIcon face = null;
switch(cube)
{
case 1:
ImageIcon face1 = new ImageIcon("Die_Face_1.png");
face = face1;
break;
case 2:
ImageIcon face2 = new ImageIcon("Die_Face_2.png");
face = face2;
break;
case 3:
ImageIcon face3 = new ImageIcon("Die_Face_3.png");
face = face3;
break;
case 4:
ImageIcon face4 = new ImageIcon("Die_Face_4.png");
face = face4;
break;
case 5:
ImageIcon face5 = new ImageIcon("Die_Face_5.png");
face = face5;
break;
case 6:
ImageIcon face6 = new ImageIcon("Die_Face_6.png");
face = face6;
default:
}
return face;
}
From your description, it seems your getDie1Image()
method is a public member function of the `PairOfDice' class. This means you need to create a PairOfDice object in your class. Your new code should look like this:
public static void getImage()
{
PairOfDice pod = new PairOfDice();
JLabel face1 = new JLabel(" ", pod.getDie1Image(), SwingConstants.CENTER);
JLabel face2 = new JLabel(" ", pod.getDie2Image(), SwingConstants.CENTER);
}
Remember that in Java, you can only call public member functions of other classes by creating an instance of that class and accessing its member like so:
SomeClass sc = new SomeClass();
sc.my_pub_member_fxn();
If the public method were also static, you wouldn't need to create an instance of the class since static methods belong to the class itself, not an instance of the class. Your code then would be:
SomeClass.my_pub_member_fxn();