Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7585147
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T19:06:15+00:00 2026-05-30T19:06:15+00:00

I’m making a text based RPG to help me learn Java. So I have

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T19:06:16+00:00Added an answer on May 30, 2026 at 7:06 pm

    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:

    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    
    import javax.swing.*;
    
    public class DependInjectEg {
       private static void createAndShowGui() {
          Player[] players = {
                new Player("John Smith", 10, 5),
                new Player("Donald Duck", 8, 3),
                new Player("Doris Day", 5, 2),
                new Player("Bill Jones", 4, 6),
                new Player("Frank Stein", 1, 1),
          };
    
          PlayerStats mainPanel = new PlayerStats();
          for (Player player : players) {
             mainPanel.addPlayer(player);
          }
    
          JFrame frame = new JFrame("Dependency Injection Example");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    class Player {
       private String name;
       private int speed;
       private int strength;
    
       // default constructor
       public Player() {
       }
    
       public Player(String name, int speed, int strength) {
          this.name = name;
          this.speed = speed;
          this.strength = strength;
       }
    
       public int getStrength() {
          return strength;
       }
    
       public void setStrength(int strength) {
          this.strength = strength;
       }
    
       public String getName() {
          return name;
       }
    
       public void setName(String name) {
          this.name = name;
       }
    
       public int getSpeed() {
          return speed;
       }
    
       public void setSpeed(int speed) {
          this.speed = speed;
       }
    
       @Override
       public String toString() {
          StringBuffer sb = new StringBuffer();
          sb.append("Name: " + name + ", ");
          sb.append("Speed: " + speed + ", ");
          sb.append("Strength: " + strength);
    
          return sb.toString();
       }
    
    }
    
    @SuppressWarnings("serial")
    class PlayerStats extends JPanel {
       private DefaultListModel playerListModel = new DefaultListModel();
       private JList playerList = new JList(playerListModel);
    
       public PlayerStats() {
          JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
          btnPanel.add(new JButton(new NewPlayerAction()));
          btnPanel.add(new JButton(new EditPlayerAction()));
          btnPanel.add(new JButton(new ExitAction()));
    
          setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
          setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("Player Stats"),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));
          add(new JScrollPane(playerList));
          add(Box.createVerticalStrut(5));
          add(btnPanel);
    
       }
    
       public void addPlayer(Player player) {
          playerListModel.addElement(player);
       }
    
       private class NewPlayerAction extends AbstractAction {
          public NewPlayerAction() {
             super("New Player");
             putValue(MNEMONIC_KEY, KeyEvent.VK_N);
          }
    
          public void actionPerformed(ActionEvent evt) {
             PlayerEditorPanel editorPanel = new PlayerEditorPanel();
             int result = JOptionPane.showConfirmDialog(PlayerStats.this,
                   editorPanel, "Create Player", JOptionPane.OK_CANCEL_OPTION,
                   JOptionPane.PLAIN_MESSAGE);
             if (result == JOptionPane.OK_OPTION) {
                Player player = editorPanel.getNewPlayer();
                playerListModel.addElement(player);
             }
          };
       }
    
       private class EditPlayerAction extends AbstractAction {
          public EditPlayerAction() {
             super("Edit Player");
             putValue(MNEMONIC_KEY, KeyEvent.VK_E);
          }
    
          public void actionPerformed(ActionEvent evt) {
             Player player = (Player) playerList.getSelectedValue();
             if (player == null) {
                return; // do nothing if no player selected
             }
             PlayerEditorPanel editorPanel = new PlayerEditorPanel();
             editorPanel.setPlayer(player);
    
             int result = JOptionPane.showConfirmDialog(PlayerStats.this,
                   editorPanel, "Edit Player", JOptionPane.OK_CANCEL_OPTION,
                   JOptionPane.PLAIN_MESSAGE);
             if (result == JOptionPane.OK_OPTION) {
                editorPanel.upDatePlayerAttributes();
                playerList.repaint();
             }
          }
       }
    
       private class ExitAction extends AbstractAction {
          public ExitAction() {
             super("Exit");
             putValue(MNEMONIC_KEY, KeyEvent.VK_X);
          }
    
          public void actionPerformed(ActionEvent e) {
             Window win = SwingUtilities.getWindowAncestor(PlayerStats.this);
             win.dispose();
          }
    
       }
    }
    
    @SuppressWarnings("serial")
    class PlayerEditorPanel extends JPanel {
       public static final String[] FIELD_TITLES = { "Name", "Speed", "Strength" };
       private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
       private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
       private JTextField nameField = new JTextField(10);
       private JTextField speedField = new JTextField(10);
       private JTextField strengthField = new JTextField(10);
       private JTextField[] fields = { nameField, speedField, strengthField };
       private Player player;
    
       public PlayerEditorPanel() {
          setLayout(new GridBagLayout());
          setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("Player Editor"),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));
          GridBagConstraints gbc;
          for (int i = 0; i < FIELD_TITLES.length; i++) {
             gbc = createGbc(0, i);
             add(new JLabel(FIELD_TITLES[i] + ":", JLabel.LEFT), gbc);
             gbc = createGbc(1, i);
             add(fields[i], gbc);
          }
       }
    
       @SuppressWarnings("static-access")
       private GridBagConstraints createGbc(int x, int y) {
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.gridx = x;
          gbc.gridy = y;
          gbc.gridwidth = 1;
          gbc.gridheight = 1;
    
          // bad coding habit using variable name to access static constants
          // done for sake of brevity and clarity
          gbc.anchor = (x == 0) ? gbc.WEST : gbc.EAST;
          gbc.fill = (x == 0) ? gbc.BOTH : gbc.HORIZONTAL;
    
          gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
          gbc.weightx = (x == 0) ? 0.1 : 1.0;
          gbc.weighty = 1.0;
          return gbc;
       }
    
       public void setPlayer(Player player) {
          this.player = player;
          nameField.setText(player.getName());
          speedField.setText(String.valueOf(player.getSpeed()));
          strengthField.setText(String.valueOf(player.getStrength()));
       }
    
       public Player getNewPlayer() {
          String name = nameField.getText();
          int strength = 0;
          try {
             strength = Integer.parseInt(strengthField.getText());
          } catch (NumberFormatException e) {
             // TODO: notify user that field was empty
          }
          int speed = 0;
          try {
             speed = Integer.parseInt(speedField.getText());
          } catch (NumberFormatException e) {
             // TODO: notify user that field was empty
          }
    
          Player p = new Player();
          p.setName(name);
          p.setSpeed(speed);
          p.setStrength(strength);
    
          return p;
       }
    
       public void upDatePlayerAttributes() {
          String name = nameField.getText();
          int strength = 0;
          try {
             strength = Integer.parseInt(strengthField.getText());
          } catch (NumberFormatException e) {
             // TODO: notify user that field was empty
          }
          int speed = 0;
          try {
             speed = Integer.parseInt(speedField.getText());
          } catch (NumberFormatException e) {
             // TODO: notify user that field was empty
          }
    
          player.setName(name);
          player.setSpeed(speed);
          player.setStrength(strength);
       }
    }
    

    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:

    public void setPlayer(Player player) {
      this.player = player;
      nameField.setText(player.getName());
      speedField.setText(String.valueOf(player.getSpeed()));
      strengthField.setText(String.valueOf(player.getStrength()));
    }
    

    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:

      public void actionPerformed(ActionEvent evt) {
    
         // *** first get the selected Player from the JList
         Player player = (Player) playerList.getSelectedValue();
         if (player == null) {
            return; // do nothing if no player selected
         }
    
         // then create a PlayerEditorPanel object
         PlayerEditorPanel editorPanel = new PlayerEditorPanel();
    
         // and then "inject" the selected Player into the editor panel.
         editorPanel.setPlayer(player);
    
         // and display it in a JOptionPane
         int result = JOptionPane.showConfirmDialog(PlayerStats.this,
               editorPanel, "Edit Player", JOptionPane.OK_CANCEL_OPTION,
               JOptionPane.PLAIN_MESSAGE);
         if (result == JOptionPane.OK_OPTION) {
            editorPanel.upDatePlayerAttributes();
            playerList.repaint();
         }
      }
    

    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:

    public void upDatePlayerAttributes() {
      String name = nameField.getText();
      int strength = 0;
      try {
         strength = Integer.parseInt(strengthField.getText());
      } catch (NumberFormatException e) {
         // TODO: notify user that field was empty
      }
      int speed = 0;
      try {
         speed = Integer.parseInt(speedField.getText());
      } catch (NumberFormatException e) {
         // TODO: notify user that field was empty
      }
    
      player.setName(name);
      player.setSpeed(speed);
      player.setStrength(strength);
    }
    

    Make sense?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a bunch of posts stored in text files formatted in yaml/textile (from
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a text area in my form which accepts all possible characters from
I have a reasonable size flat file database of text documents mostly saved in
I have thousands of HTML files to process using Groovy/Java and I need to
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
I am trying to loop through a bunch of documents I have to put
link Im having trouble converting the html entites into html characters, (&# 8217;) i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.