Using multiple JButtons with the same label in Java

前端 未结 3 380
温柔的废话
温柔的废话 2020-12-12 07:26

I have two buttons in my project that both have a \"+\" label. When the actionPerformed() method is called, it calls a specific method based on the label. How can I distigui

3条回答
  •  轮回少年
    2020-12-12 07:38

    You could...

    Use ActionEvent#getSource

    You could...

    Set the actionCommand property of each button to something unique and use ActionEvent#getActionCommand

    You could...

    Use separate listeners, either anonymously or as inner or outer classes depending on your needs

    You could...

    Make use of the Action API, which would allow you to define a common/abstract Action which defined the common properties (like the + text) and then extend this to make unique actions for each button

    See How to Use Actions for more details

    You could...

    Use JButton#putClientProperty to set some unique flag on each button and cast the ActionEvent to a JComponent and use getClientProperty to retrieve the flag ... but given the previous suggestions, I'm not sure why you'd bother

提交回复
热议问题