Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the best place to register listeners to JButtons created from arrays?

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.

like image 642
Adam Smith Avatar asked Dec 12 '25 00:12

Adam Smith


1 Answers

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.

like image 142
Hovercraft Full Of Eels Avatar answered Dec 14 '25 14:12

Hovercraft Full Of Eels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!