-1

So I have two classes: "Simulator" and "SimulationWindow". Simulator holds all methods and functions the Simulator uses and also defines an instance of SimulationWindow.

SimulationWindow makes the GUI. In this GUI I have 4 JButtons. These buttons should call methods implemented in Simulator. But how can I connect the buttons with the listener?

button1.addActionListener( ??? );

I struggle because my program has a main class to start the Simulator:

Simulator sim1 = new Simulator();

So I have this object Simulator and cannot create another one in SimulationWindow?

Boann
  • 48,794
  • 16
  • 117
  • 146
da1m
  • 3
  • 1

2 Answers2

1

Pass the reference to your Simulator to the SimulationWindow's constructor and save it in a field there:

In Simulator:

class Simulator {
    private final SimulationWindow window;

    public Simulator() {
        window = new SimulationWindow(this);
    }

    ...
}

In SimulationWindow:

class SimulationWindow extends JFrame { 
    private final Simulator sim;

    public SimulationWindow(Simulator sim) {
        this.sim = sim;
    }

    ...
}

Then you can access sim within the instance of SimulationWindow and within the ActionListeners you add there.

Boann
  • 48,794
  • 16
  • 117
  • 146
0

you can add the actionPerformed method in the inner class(SimulationWindow) and have a look at here on how to call outer class(Simulator) methods from the inner class context.

Community
  • 1
  • 1
mosemos
  • 71
  • 3
  • I tried this, getting "No enclosing instance of the type Simulator is accessible in scope" - Error. – da1m Dec 27 '14 at 13:45