the getSource() and getActionCommand()

前端 未结 4 1412
庸人自扰
庸人自扰 2021-02-02 11:04

What is getSource? and what does it return?

and what is getActionCommand() and what does it return??

I am getting confused between these two can anyone give or d

4条回答
  •  有刺的猬
    2021-02-02 11:54

    getActionCommand()

    Returns the command string associated with this action. This string allows a "modal" component to specify one of several commands, depending on its state. For example, a single button might toggle between "show details" and "hide details". The source object and the event would be the same in each case, but the command string would identify the intended action.

    IMO, this is useful in case you a single command-component to fire different commands based on it's state, and using this method your handler can execute the right lines of code.

    JTextField has JTextField#setActionCommand(java.lang.String) method that you can use to set the command string used for action events generated by it.

    getSource()

    Returns: The object on which the Event initially occurred.

    We can use getSource() to identify the component and execute corresponding lines of code within an action-listener. So, we don't need to write a separate action-listener for each command-component. And since you have the reference to the component itself, you can if you need to make any changes to the component as a result of the event.

    If the event was generated by the JTextField then the ActionEvent#getSource() will give you the reference to the JTextField instance itself.

提交回复
热议问题