GetActionCommand () vs getSource ()

For the longest time, I have been calling getActionCommand

into ActionEvent

objects to extract information from some JButton

s, but as my programs got more complex I wanted to send a few bits of information through setActionCommand

, i.e. having a command like "r3" to indicate Action Listener

that I wanted r , pop the 3 rd button from the panel within JFrame

. Eventually I got tired of parsing strings and extracting information that I wanted to use and started using instead getSource

. (I want to know which one is better to use for information retrieval)

Also, I created a subclass JButton

called OperationButton

which has two instance fields, int

ID and Operation

op (which Operation

is a custom enumerated type whose values ​​are ADD, REMOVE, SWITCH, etc.). I want to know if there is a more efficient / more efficient method than just using getActionCommand

, or if there is a third way to handle events that I haven't thought of yet.

public void actionPerformed(ActionEvent e)
   OperationButton opButton = (OperationButton) e.getSource();
   int ID = opButton.getID();
   Operation op = opButton.getOperation();

   switch (op)
    case ADD: //adds a custom panel to frame
    case REMOVE: //removes a button and a custom panel with the specified ID 
    case SWITCH: //highlights a button with the specified ID and 
                 //displays a custom panel with the specified ID


(OperationButtons are the only buttons in my program)

Again, I want to get information without having to set an action command JButton

, but I'm not entirely sure if this is the right way. Also, will this method be feasible for future programs where I can send more than 2 pieces of information?


source to share

All Articles