Sorry if this is obvious, but I haven't done this before.
I've made a JFrame subclass that, upon the user clicking the Input button on the main GUI, will pop up and allow the user to enter some data, after which the user clicks OK or Cancel to return that data to the main GUI.
Sounds easy enough, but how to implement it? The button on my main Frame can call a method to create the pop-up instance of a JFrame subclass that I've called InputFrame, but how to get the data back, when the user clicks the "Done" button?
I could pass a reference (this) to the InputFrame which could be stored as a private variable and used to invoke a method on the GUI when the user hits Done. But this isn't exactly the same as just returning the data I need to the method that called it. And doesn't seem like good encapsulation, since I need to hard code into the InputFrame the name of the method in the GUI I want to use to handle the value returned. Whereas perhaps I want to access this data from several different places for different purposes (OK, I don't, but you see what I mean). There must be a standard way to do this - any pointers? Thanks.
First off, it's usually better to show data entry forms in a modal dialog, not a second frame. FWIW, here's a generalization of how I might tackle this (typed here, not compiled nor tested)Hm, I'm not happy with the return null but it doesn't directly detract from a demonstration of an approach to the issue.
Also, subclassing a JFrame or any other class where there isn't a need to change the default behavior is a misuse of inheritance. Favor composition.
There are no new questions, but there may be new answers.
Great, thanks. A JOptionPane / JDialog looks like just what I need (I haven't used them before). Your example makes it clearer, the message being to create the component from which you want to get the data within your method for retrieving data.
The main thing I didn't understand was modality - basically how to get the application to wait for the user input. Not understanding that, the source for JOptionPane.showOptionDialog(...) (below) looks a bit strange with
in the middle! The show() method seems to deal with the business of locking up threads and using the Object.wait() method beind the scenes.
It seems I would be barking up the wrong tree with JFrame since there doesn't seem to be a way to make them modal.
I'll have a go at implementing JDialog and report back if I have problems. (Incidentally I did get it working with a JFrame but in the way I described in the OP, so it's a bit of a kludge.)
I miss the old days when I would think up a sinister scheme for world domination and you would show a little emotional support. So just look at this tiny ad: