Hi Code Ranch. I just stumbled upon another exercise in the book I'm practicing with that just gave me a hard time. Can I add actionListener to a button component without creating a reference to it? Look at my code below:
Or should I just do the usual instance.addActionListener(this) like myButton.addActionListener(this)? Please help and give me advice. Thank you!
Ryan Daguman wrote:Can I add actionListener to a button component without creating a reference to it?
Sure you can
You can use the concept of an anonymous class along with the JButton constructor public JButton(Action a) Since Action is an interface, and you just wish to do execute some code on the button click, you can make your anonymous class an instance of AbstractAction.
Essentially you will have something like
You could even create some kind of builder class that hides some of the hidiousness of assembling a Swing GUI behind a more fluent API / internal DSL, or find an existing implementation that fits (recommended).
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Thanks for your reply. I think the AbstractAction method is kind of advanced for me right now as a beginner in Java. However, I was able to successfully finish the program by creating instances of the button for the different colors in order to change the background. Please refer below:
Can you further help me with using the AbstractAction() method (that I believe is included in the javax.swing package) with a kind of longer example using my code above? Thank you.
I would get a better book. You code is using "Button". That is an AWT components. You should be using JButton, which is a Swing component. Anything that teaches you to use AWT should be avoided. People have been using Swing for well over a decade now.
That is not how you add components to a Container. First of all you should NOT be hardcoding constraints. Every layout manager will have a variable for the appropriate constraint. Secondly the constraint should NOT be the first parameter of the method. Read the API for the appropriate method signature to use.
I would suggest you use the Swing Tutorial to learn the basics of Swing. You can many use your book for exercise suggestions, but the solution should be implemented with Swing.