I have a class that extends JPanel. In its constructor I'm passing this
to other methods, mainly to add the jpanel object as a listener to containers/controls within the jpanel (but also other objects). Since Netbeans shows a leaking this in constructor
warning for those calls I've put them in an other method that is called from the constructor.
before:
class Foo ... {
public Foo() {
initComponents();
tabX.addChangeListener(this); // <- netbeans complains here
}
after:
class Foo ... {
public Foo() {
initComponents();
initListeners();
}
protected void initListeners() {
tabX.addChangeListener(this);
}
That gets rid of the symptom. But I doubt it fixes the reason why netbeans shows the warning.
Where is the proper place to do this kind of initialization in a JPanel-derived class?
I wonder if there's a bigger issue at play here -- that of asking your class to do too much. A class should have one main purpose, and a view should be responsible for view and that's it. To have it do model or control functions and you lose cohesion, may increase coupling and risk creating god objects that are difficult if not impossible to debug or extend. So to put it bluntly, your GUI or view classes should not also be listener classes. In other words, there is no good reason and a lot of bad reasons for a GUI class to also implement a listener interface.
The best solution: don't have your GUI classes implement listeners. Instead either use anonymous inner classes, or private inner classes, or if complex enough or you anticipate extending and/or modifying your code in the future, stand alone listener classes.
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