In Java, the Swing library implements the Observer/Subscriber-Publisher design pattern to design the way the program responds to events on the GUI (button clicks, etc).
The programmer registers ActionListener
objects (the observers) to a GUI element (the subject/observable/publisher), and these objects get notified by the GUI element when it’s state is changed, and do something accordingly. This seems a reasonable way to design a GUI system, and I can’t think of any other way a framework could do this.
Is there any other way to design an event-response system in a GUI? Are there any imperative-language frameworks or libraries with a GUI event-response system not designed this way? Does the event-response system in the most common C# GUI library implement event-response issues using Observer, or something else? What about libraries for Python, etc.
There’s functional reactive programming. The idea is to turn time-varying entities into first-class objects. Suppose we’re dealing with a mouse cursor, and we want to draw an icon 10 pixels to the right of the cursor. Imagine that there was a type TimeVarying<T>
that represents a value that changes over time. TimeVarying always magically contains the current value of that quantity. So instead of registering a callback and doing a bunch of imperative things to grab the current mouse position and update the position of the icon, imagine the mouse position was a TimeVarying<Point>
. Then, we could write something like…
iconX = mousePosition.x + 10;
And the iconX variable would also be a time-varying quantity. Whenever the mousePosition changes, iconX would change, much like cells in a spreadsheet. Naturally, there needs to be something that’s keeping all these values current and propagating the changes in a safe and efficient way.
For more details, see the paper Deprecating the Observer Pattern.
I know functional reactive programming frameworks exist, but I don’t know if there’s any mature frameworks for Java.
2
Swing also allows you to inherit the panels and override the Process*Event
methods from the core Container class , you need to enable the events first though.
This is only a good idea if you are creating a new complex widget though