0

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.

CodeJunky78
  • 13
  • 1
  • 5
  • 3
    If you have different operations for each button, you should probably have separate event handlers for each. Chains of `if` or `switch` just to do different operations on different objects are usually a sign of incorrect design. – RealSkeptic Aug 02 '15 at 20:01
  • I completely agree with RealSkeptic. Why would a switch stack be less of a giant mess than a if/else stack. They do the same thing, except switch is worse, since it falls through if you forget to break. One listener per button is much, much better. – JB Nizet Aug 02 '15 at 20:10
  • To clarify, the actual event handling logic is handled by a separate, external handler for each object. The switch / if determines which handler in the handler class to call. I see what you're saying though. Rather than using a switch / if in the class containing the objects, I can simply call the appropriate method in the handler class directly. Much simpler. Thanks. – CodeJunky78 Aug 02 '15 at 20:24

1 Answers1

-2

You need to use setName() for the component form which you are getting an event. Then you will not get null value instead you will get whatever you will set. For example :

JButton jButton =new JButton();
jButton.setName("name");

On the other side when you get event:

event.getSource().getName();