This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I am working my way through some GUI stuff using the Murach book on Java SE 6. I am using his code to make a JPanel, but I keep getting something that says, "Leaking this in Constructor". I know why this can potentially be bad and how to fix it. However, I have seen this a lot in various places. Since I don't really have a lot of experience with GUI's, does anyone know if this is really a problem where GUI's are concerned? And most importantly for this discussion, are the test examiners going to have a cow if/when they see it? Here is the snipped I am referring to:
I realize I can use hidden inner classes to create these action listeners, but given that NetBeans keep flashing me this problem I'd like to fully understand it.
The warning you're receiving in Netbeans arises because you're attempting to pass "this" (a reference to the current instance) into a method when that instance may not have been fully constructed yet. After all, you're in the middle of constructing "this".
For kicks, switch the order of the second and third lines (so that 'addActionListener(this)' comes last) and see whether the IDE still complains. If it still whines when passing 'this' comes last, you can also suppress those warnings somewhere in the IDE's configuration.
(If "Panel" is really the name of your subclass of JPanel, then you might consider using a more descriptive name, too.)
Yeah it still gives me an error regardless of where I put it. I guess I am just being over paranoid. I know the exam people will take a fine tooth comb to my code, so I am doing to the same. I can fix it fairly easily, but since I have seen more than one well known Java author create code like this, I didn't know how big a deal it would be if a grader saw this in my own code. Of course, with a couple lines of code it all goes away, but I don't want them to deem my code "less clear" because of it.
As for the name, I am just playing around for the moment before I get started with the nuts and bolts of the test.