Attaching A Single Action Listener To All Buttons

后端 未结 4 2042
孤街浪徒
孤街浪徒 2020-11-29 13:07

I have a program with many buttons, all of which will be performing the same function. I was wondering if there was a way to attach a single listener to all existing JButton

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 13:43

    There are many ways to do it.

    Do you control creation of these buttons? If yes, create a factory and attach a listener before returning the object

    Otherwise, you may traverse swing tree and check for instance of JButton and attach on a match

    You can also think about ActionMap/InputMap approach where an action can be stored and invoked based on the focus policy.

    Also, you may extend JButton....

提交回复
热议问题