Multiple if then else on a listener class

69 views Asked by At

Is there neater/simpler way of executing if-then-else statements using a listener's getSource()?

I've got a FocusListener that I need to highlight the text in the JTextField that triggered the FocusListener

    private class calculator implements FocusListener{ 


        public void focusGained(FocusEvent evt) {


            if(evt.getSource()==txtInitialRead ){   


                txtInitialRead.selectAll(); 

            }

My problem is that I have quite a lot of JTextFields and would need to create an if statement in the FocusListener for each one. Is there any easy method of doing this? Switch branches do not work for this object type.

Of course this isn't a huge deal, I just think there must be a neater way to do this.

Thanks!

1

There are 1 answers

3
Hovercraft Full Of Eels On

Simply highlight the current component:

@Override
public void focusGained(FocusEvent evt) {
    JTextComponent tComponent = (JTextComponent) evt.getSource();
    tComponent.selectAll();
}

Any JTextField (or other textcomponent) that has this listener will have all text selected if/when it gains focus.

Just don't add this listener to a non-text component or you risk throwing a class cast exception.