I’m making a text based RPG to help me learn Java. So I have a bunch of different classes that make swing forms right now and each of which will lead to one another. However, in one form I actually create the instance of the object called Player, where I will set the stats (strength, agility, level, etc.) based on the choices the user makes.
However, I can only access that object in that class/window and I can’t call it for manipulate that object anywhere else in the application.
How do I make it globally accessible?
Edit
I should have phrased this better. Let’s say I have a class called PlayerCreation and in PlayerCreation I make an object by calling the Player class Player p1 = new Player(); Now I move out of that class completely and go to another form called PlayerStats and I want to call p1.getStrength(); but since p1 was in PlayerCreation class, I can’t get it.
Here’s an example of what I’m talking about. I’ll add some text in a bit, but if you compile and run this code, you’ll see how it works:
The Player class is a simple class that has 3 Player attributes — name, strength and speed.
The PlayerStats class is the main GUI class that holds a bunch players in a JList’s model and has functionality to add or edit players.
The PlayerEditor is a class that displays the stats of a single player and allows creation of new players or editing of current player attributes in JTextFields. If you want to edit an existing Player, you “inject” the Player object into this class via the
setPlayer(Player player)method:This will display the Player’s attributes in the JTextField and will set an internal private variable player to refer to this injected Player object. This is called in the PlayerStats class like so:
Then later if you decide that you want to accept the changed attributes, you’d call the
upDatePlayerAttributes()method which would give those attributes to the Player object held by the player variable:Make sense?