0

In my View class I have multiple custom panel classes(extending JPanel) as nested classes, that communicate with each other when changes happen. I'd like to make those panels separate classes, each in own file for readability. But that way those panels can't directly call each others methods. Should I give each panel references to other panels, or to view class? All this seems like its not good idea and everything is tightly coupled. What would be best solution or good design to solve this? Would adding property listeners or using observer pattern be the right way?

JacekQ.
  • 21
  • 5
  • 1
    Perhaps this [SO Post](https://stackoverflow.com/questions/14186199/communication-between-two-jpanels) can help you out! – gtgaxiola Aug 01 '18 at 21:11
  • 1
    Or this [SO Post](https://stackoverflow.com/questions/7053283/sending-messages-between-two-jpanel-objects) – gtgaxiola Aug 01 '18 at 21:12

1 Answers1

1

Learn about the Observer pattern.

enter image description here

In short, if JPanel "A" must refresh when changes are done in JPanel "B" then

JPanel "B" must implement the Subject interface

  • Since JPanel "B" is implementing the Subject interface, it must implement three methods.
  • The attach method which register objects (Observers) that wish to be notified when there is an update.
    • This is just adding an object to an ArrayList
  • The detach method which unregistered objects (Observers)
    • This is just removing such object from the Arraylist
  • The Notify method which goes thought all the objects in the ArrayList and calls the update method

JPanel "A" must implement the Observer interface

  • Since JPanel "A" implements the Observer interface, it must implement one method:
    • The update method is going to be called by the Subject when its notify method is called.
      • Your update method should tell JPanel "A" what to do. For example, it could check for a value in JPanel "B"

Example of Interaction

  • JPanel "A" register in JPanel "B".
  • A property in JPanel "B" is changed which triggers the method notify() which notifying all Observers (in this case JPanel "A") that there was a change.
  • This means JPanel "B" calls the update() method of all observers that registered.
  • JPanel "A" has update() method executed which makes JPanel "A" to check a property in JPanel "B" and update accordingly.

Let me know if this explanation makes sense to you.

acarlstein
  • 1,799
  • 2
  • 13
  • 21