For the longest time I have been invoking getActionCommand
on ActionEvent
objects to retrieve information from some JButton
s, but as my programs grew more complex, I wanted to send several bits of information through setActionCommand
, i.e. having a command like "r3" to indicate to the Action Listener
that I wanted to remove the 3rd button from a panel within a JFrame
. Eventually, I grew tired of parsing the strings and extracting the information that I wanted to use and instead started using getSource
. (I want to know which one is better to use to retrieve information)
Also, I created a subclass of JButton
called OperationButton
that has two instance fields: an int
ID and an Operation
op (Operation
is a custom enumerated type whose values are ADD, REMOVE, SWITCH, etc). I want to know if the following method is more efficient/a better practice than simply using getActionCommand
, or if there is a third way of handling events that I have not 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
break;
case REMOVE: //removes a button and a custom panel with the specified ID
break;
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 retrieve information without having to set the action command of a JButton
, but I'm not entirely sure if this is the right way to go. Also, would this method be feasible for future programs in which I might want to send more than 2 pieces of information?