Home > Net >  How to create and keep a constant object from start to end
How to create and keep a constant object from start to end

Time:05-18

I am building a Java Swing application (a game).

One question I couldn't solve was how to initiate a class object at the launch of the application that acts as a overall manager to store the player and other game data on

If I created a Player() object in one screen, would the same object stay alive after the closure of the screen it was created on? Or would it terminate along with the screen?

i.e. '''

    public class PlayerSetup {
             private JFrame frame;
             private JTextField nameInput;

    public PlayerSetup() {
            initialize();
    }

    private void initialize(){
            nameInput = new JTextField();
            nameInput.setText("John Doe");
            JButton confirmButton = new JButton; 
            
            //upon mouseClicked action on confirm Button
            Player onlyPlayer = new Player(String nameInput);

    }

    //later on, 

      PlayerSetup.close() 

'''

After closing the PlayerSetup window, would the onlyPlayer object stay alive?

If it lives, would this be callable from subsequent windows?

If it dies, what would be the best method to keep data?

Thank you in advance!

CodePudding user response:

You should use a the singleton design pattern. Here is a good tutorial : singleton tuto

CodePudding user response:

er.. the comment that had the answer disappeared.......

Just changed Player() class to singleton :D

Thank you, first commenter! >w</

  • Related