I'm creating some JButtons from a String array for a menu. Those buttons are created in a class that extends JButton. On creation, the buttons call a method to create some children buttons (if the parent button has a submenu to display).
I'd like to be able to register listeners to every single button. Each button is going to either change the JPanel currently displayed or open up its submenu. I thought I'd register the listener in the constructor, but I read some articles I found on Google that it was bad practice to do so.
What I'd like to know is where the best place to do this would be, because I have no idea what's good practice and what's not when registering listeners.
I think I know what's confusing you. This article: Java theory and practice: Be a good (event) listener states that it is bad practice to register a listener from its constructor, but what they mean is the listener's constructor, not the button' constructor. It should be fine to register a listener from within the JButton's constructor. Your listener will likely be an anonymous inner class or an inner private class (or if complex, a stand alone class), so this is not really an issue.
edit
Except you can have problems if you do this and then subclass your buttons.
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