Search code examples
javaswingclassinstances

Access class instance that is initialised in action event java


I am trying to have one class read a variable belonging to one instance of another class. The class that is being read from is only initiated once a JButton is pressed. From my experimenting it seems that I am unable to access any of the class's variables (maybe because the compiler isn't certain the first class will actually be initiated?)

Does anyone know of a way around this?

sorry about the vagueness.

public class MainClass extends JComponent implements ActionListener{
   JButton button = new JButton("Run Program");
   MainClass INSTANCE = new MainClass()  // create an instance of the main class to refer to later
        constructor(){

        this.add(button);
        button.addActionEventListener(this);
        }

    actionPerformed(ActionEvent e){
    if(e.getSource == button){
     NextClass nextClass = new NextClass();  // class being read from
     FinalClass finalClass = new FinalClass(); // class doing the reading
    }



   public class NextClass{
   boolean state = true; // what is being read

    constructor(){}
   }



    public class FinalClass{
    constructor(){
    if(MainClass.INSTANCE.nextClass.state == true){do something...}
    }
    }

Basically, the nextClass and finalClass instances get created when the button is pressed. inside the Final class I want to check the state variable in the nextClass instance of the NextClass Class. I dont seem to be able to gain accesses to the state variable or any other variable or function in the next class. My assumption being because there isnt a guarantee that the nextClass will actually be initiated?


Solution

  • Okay I think I figured out how to do it. I couldnt initialise nextClass in mainClass because then it would start running pre-emptively, and simply declaring it wasn't doing the trick either.

    The solution was creating a new constructor for next class that accepts a parameter. the constructor would however be empty (no methods to call or anything). This way I could initialise nextClass without causing it to run its methods pre-emptively.