I am writing a Java application using SWT widgets. I would like to update the state of certain widgets upon a certain event happening (for example, updating the data model’s state).
Is there something in Java similar to Cocoa’s NSNotificationCenter, where I can register an object to listen for notification events and respond to them, as well as have other objects ‘fire off’ a notification?
Ok, suppose that for example, you want parts of your program to be notified when your Loader starts a scan, and when it finishes a scan (don’t worry about what a Loader is, or what a scan is, these are examples from some code I have lying around from my last job). You define an interface, call it ‘ScanListener’, like
Now the Loader defines a method for your other code to register for callbacks, like
The Loader, when it starts a scan, executes the following code
and when it finishes, it does the same thing with listener.scanCompleted();
The code that needs to be notified of these events implements that interface (either themselves, or in an internal class), and calls ‘loader.addScanListener(this)’. Its scanStarted() and scanCompleted() methods are called at the appropriate times. You can even do this with callbacks that take arguments and/or return results. It’s all up to you.