I learned recently (in a class based on C#) that it's sometimes considered dangerous to register event listeners in an object's constructor, because those event listeners are given a reference to that object before the object is fully initialized, and could (at least in theory) attempt to access the object before construction is complete.
From what I understand, accessing an object before construction is complete can cause a crash, at least in some languages...if it doesn't cause a crash, then we would only care that the registration occur last, so our object is ready to receive events when we register its listeners.
I'm now starting on a new Swing GUI, and noticed that my standard practice when building Swing GUIs is to wire up the event listeners in the constructor.
It seems unlikely that the event listeners of Swing components would be called before the constructor is complete, as they presumably are not wired up until the component is added to a visible Swing container, which can only happen after construction.
So, is there a real reason to avoid that anti-pattern when working in Swing? And if so, what is the simplest way to go about it?
As long as you assign your event listeners in the UI thread than you'll be fine.
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