I'm creating a number of event handlers and to keep things clean, rather than having a massive stack of if...else for the 20+ objects that could be the source in each handler, I'm trying to use a switch-case. The issue, of course, is that you can not switch on an Object, which event.getSource(); returns, and following it with .toString() returns nothing that can be easily used for each case. What I'm wondering is if there is a way to get the name of the event source object in a string, which can be used in a switch. The text of a button, rather than its name, could work as well, but I'm also trying to do this with textboxes, in which case only the name will really work. I've only come across one solution, but it does not work for some reason.
public class EntryHandler implements ActionListener
{
@Override
public void actionPerformed( ActionEvent event )
{
if( event.getSource() == addEntryButton )
{
Object source = event.getSource();
String bString;
if (source instanceof JButton)
{
bString = ((JButton) source).getName();
} else {
bString = "Wrong";
}
System.out.printf("b name: %s", bString);
entryData.addTableEntry();
} ... more if's for other buttons...
for some reason, this always prints "b name: null"
I could always just use the if...else stack, which is how it is currently implemented, but it looks like a giant mess. Any suggestions or alternatives would be appreciated.