I'm supposed to be creating a game, and we've been given free rein in creating it...but I have no idea what I'm doing. I copied the format of a previous lab, because I needed a way to run it, but now I have a problem. My Gui class is as follows:
public class Gui implements Runnable {
public Gui() { }
ArrayList<Tile> _al;
@Override
public void run() {
//where I want the _al variable to be used
}
}
The code I copied used a Driver class to run this method:
public class Driver {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Gui());
}
}
We haven't discussed this method in class, but from Googling I understand that this is necessary for the program to work. There's been a massive jump in the difficulty of the labs, so I am now lost. I'm sure there's a simple way to format all the code, but I have no idea what the relationship is between the run method and the main, or how I can make it so an association relationship can be made in my code. Nothing I've searched really helped, so I hope this question's okay.
How to associate an instance variable if all the code is inside a run() method?
You've done it right. You can use _a1
in the run
method.
_a1
is an instance variable. You can tell this because it does not have the static
modifier. Likewise, run
is an instance method. Therefore it has access to _a1
. Each new instance of Gui
gets its own instance of _a1
however.
If that's not what you want, the absolute simplest fix is to add the static
modifier to _a1
. Then it will be shared across all instances of Gui
and can still be accessed from run
. I believe Swing does not run runnables concurrently so there shouldn't be concerns with parallel access.