views:

57

answers:

2

Hi,

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, the 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

+1  A: 

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.

abhin4v
@abhin4v:This is a very good idea, but I still have to pass references in the gui components I want to update (of cource using EventQueue). Now because I return to the view the components are available. Any ideas?
and what is the issue with the components being available to the callback?
abhin4v
@abhin4v: No issue, I am new to swing and I was not sure if it is an approach used or there is some other kind of separation pattern. Thank you for your reply!
+1  A: 

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:

  1. Arrange for your view to implement the Observer interface and have your input window delegate to a contained instance of Observable. The notifyObservers() method may be used to pass an object reference to the Observer. A very simple example may be found here.

  2. 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 existing javax.swing.event or model the custom event on such a type. Every JComponent contains an EventListenerList.

trashgod
@trashgod: This way, the JFrame i.e. the observer will be registered for x (e.g. 4) number of JDialogs if 4 jdialogs are opened. The user presses ok from each dialog, and the same method is always called in the observer. For this to work, I should put some kind of extra information of what type of processing should happen next? Is this the way to handle this? Because now, user has dialogA and when it is closed the methodA is called in the JFrame because I know where I am in the code.
@user384706: Either approach allows passing information to the observer. I've elaborated above.
trashgod
@trashgod:I was just wondering, if the proper way is to pass some kind of e.g "doA" information and in the update(Observable o, Object arg) method of the observer I have for example a if(arg.msg =="doA") callA() else callB() etc. I am asking because I am new to gui programming and I am trying to understand the proper way to do these things. Thank you very much!
@user384706: I've added links to examples above.
trashgod