I have a JFrame and when the user presses a button is displayed an input jdialog. I need the jdialog to be in non-modal mode and once the user presses ok, I want to do some action based on the input. Right now I pass my view as reference in the jdialog, so that when the user presses ok, th开发者_JS百科e jdialog calls a method of the view. Is there a more standardized way to handle this or this is the only way? I need the jdialog to be in NON-modal mode
Thanks
You can pass a java.lang.Runnable
to be called from the JDialog when the user presses the ok button. In this way you can put the code you want to run inside the Runnable itself.
Your current approach using a callback is straightforward, but the observer pattern is commonly used to decrease the resulting tight coupling. Two implementations are typical in Swing:
Arrange for your view to implement the
Observer
interface and have your input window delegate to a contained instance ofObservable
. ThenotifyObservers()
method may be used to pass an object reference to theObserver
. A very simple example may be found here.Have your input window maintain an
EventListenerList
using a custom event in which the view registers interest. Data of interest to the listener can be passed in the event itself. It may be convenient to reuse an existingjavax.swing.event
or model the custom event on such a type. EveryJComponent
contains anEventListenerList
.
精彩评论