0

I'm trying to figure out how I can have a class listen to another. So this is the idea.

I have a MainFrame class, which is simply a container class, JFrame container, that takes an argument of type JPanel. Basically I want this container class to be able to switch between frames depending on what my other class, FrameSwitcher, will tell it to do.

The other classes are: FrameSwitcher, MainMenu and ScoreBoards.

The idea is that, let's say MainMenu, will contain 4 buttons, each one will listen, BUT will NOT change the frames. Rather it will somehow - and this is the part I need help with - send to the FrameSwitcher what button was clicked, and this information will then be sent to MainFrame to switch to the appropriate frames.

tereško
  • 58,060
  • 25
  • 98
  • 150
Van-Sama
  • 1,154
  • 4
  • 14
  • 21

2 Answers2

3

You may be looking for the observer pattern, discussed here. In particular, a PropertyChangeListener, illustrated here, may be a useful approach to loose coupling.

Also consider letting each view export an Action that selects itself from a CardLayout, as suggested in How to Use Actions and How to Use CardLayout.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

FrameSwitcher should keep ActionListeners added to the menu. On click it changes it's state and call MainFrame's method switchTo(argumentWhereToSwitch);

StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • I understand the concept, but how does `FrameSwitcher` keep `ActionListeners` added the menu? – Van-Sama Mar 16 '13 at 08:02
  • There is a `protected` instance of [`EventListenerList`](http://docs.oracle.com/javase/7/docs/api/javax/swing/event/EventListenerList.html) which is declared in `JComponent`, you can use it to maintain a list of registered `ActionListener`s. It has methods for getting all the `ActionListener`s registered as an array. You would simply then need to iterate this list and call `actionPerformed` on each – MadProgrammer Mar 16 '13 at 08:11
  • So I'm going to add the JButtons in MainMenu to the `EvenListenerList` and pass access it from `FrameSwitcher`? Then change the panels? – Van-Sama Mar 16 '13 at 08:34