Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference top-level container throughout application without making it a singleton?

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.

like image 508
mre Avatar asked Feb 21 '23 13:02

mre


1 Answers

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.

like image 118
Hovercraft Full Of Eels Avatar answered Apr 08 '23 17:04

Hovercraft Full Of Eels