How can I reference a top-level container (e.g. a JFrame
) throughout an application without making it a singleton? The reason I ask is that I'm trying to avoid the singleton antipattern.
Anyway, I find that when I need another top-level container (e.g. a JDialog
) to display a simple message to the user, I want this dialog to be placed directly over the aforementioned JFrame
using setLocationRelativeTo(frame)
. But the only way I can do so (at the moment), is to make a single instance of the JFrame
and access it using a static getInstance
method.
So, is there a way to reference a top-level container without having to resort to the singleton pattern? Please let me know if anyone needs more information!
Thanks.
If you have a reference to any Swing component held in the top level window, such as can be obtained from an Event object's (such as an ActionEvent) getSource()
method, you can use this to get the top level window via a SwingUtilities method:
SwingUtilities.getWindowAncestor(anyComponent);
This class also has other useful and similar methods such as windowForComponent(Component c)
getDeepestComponentAt(...)
and getRoot(Component c)
Otherwise you can always pass references via constructor or setter parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With