问题
I have a very specific problem, and I wanted to know if there is a way to change the owner of a JDialog (it can be set using the constructor). I suppose there is no "official" possibility (other than a hack), but I wanted to make sure I didn't miss something. Any ideas or hints on the topic would be helpful, thanks already...
回答1:
If your question is about how to reuse dialogs during your application lifecycle, then a better way is to:
- define all your dialog contents as JPanel subclasses
- and instantiate a new JDialog with the existing JPanel subclass instance
For point 2, you can of course use lazy evaluation of the panels (instantiate upon first use only, then reuse).
You will also need to have your panels implement some interface (of your own) that allows you to re-initialize them for reuse in a new JDialog (reinit typically means erasing all fields contents, or setting these fields back to their default values).
回答2:
Only thing I can think of falls under unsafe hack (use reflection and alter the owner, but that could possibly change under different version of the JVM (even from the same vensor on the same platform)).
Perhaps a better question for you to ask is "this is what I am trying to do... do I really need to change the owner of the dialog or is there a better way"? I am trying to think of reasons to want to change the owner and I cannot come up with any...
回答3:
j:
I have had a similar need for a single "global" dialog in my application to serve a "notes" dialog when the text in a table cell is too long to display. In this case, the user can hover or right-click the cell and get a dialog that displays the whole text. However, I wanted the dialog to display quickly, especially when hovering, so I wanted to simply show and hide it. I decided to create and store this dialog in the main class with the application frame as the owner. Then, whenever any view whose owner was the frame needed the notes dialog, the view could get it from the main class. In those instances where a dialog needed the notes dialog, the parent dialog could create a new instance of the notes dialog with the appropriate owner. Since these parent dialogs (in my app at least) are disposed when closed, the extra notes dialog instance would be out of scope and garbage collected. Hope that helps.
来源:https://stackoverflow.com/questions/553759/is-there-a-way-to-change-the-owner-of-a-jdialog