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 need to use an an anonymous inner class to make this work.
I don't see how that's possible. As far as I know, an anonymous inner class just creates an object from a pre-existing class, and you can override one or more of the class methods as you create the object. So, as an alternative, you could define a subclass that extends the pre-existing class, which overrides one of the pre-existing class's methods, and then you can create an object of the extended class. Same end result.
See if this helps you with your understanding of anonymous inner classes in general:
You have already created an anonymous inner class, it's in your method backgroundColoration() in class ButtonPanel.
The following lines in the constructor of class ButtonPanel are not going to compile:
Why not? Because class ButtonPanel does not implement interface ActionListener. You can't add "this" (the ButtonPanel object) as an action listener to the buttons.
Instead of this, you probably want to add the ActionListener that you've created in the method backgroundColoration() as the action listener for the buttons.
Note that at the moment, in class backgroundColoration() you are creating an instance of your anonymous inner class, but you're not doing anything with it. Also, you're not calling the method backgroundColoration() anywhere.
Basically, need to to create an anonymous instance for each button. On the plus side, you can get rid of that ugly switch statement. On the minus side, there are some scoping issues (for lack of a better term) with anonymous inner classes. For example, your switch statement checks the source of the action event and sets the background color of the current object to some color. This works because the current object is a subclass of JPanel (presumably). However, with anonymous inner classes, effectively you're dealing with completely different objects so this won't work:
The "this" reference no longer points to the instance of your original class; it points to the instance of that anonymous inner class which doesn't have a setBackground method. That's why I created the setBackgroundColor method in the first example.
I'm assuming this is for homework so this next point won't help you, but I believe that the new NetBeans GUI editor (Matisse) does all of this anonymous ActionListener stuff for you. [ October 06, 2006: Message edited by: Timothy Frey ]
Joined: Feb 03, 2005
many thanks. i've got this program running. :-)
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: ActionListener -- where to put anonymous inner class?