1

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!

Tom Bennett
  • 127
  • 1
  • 9

1 Answers1

3

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Works a charm thanks! Looks like it's back to the books to get my head around this one. – Tom Bennett Aug 17 '17 at 16:59
  • If it isn't too much to ask. Do you know of any online literature that explains the way you have created an object? The only instances of creating objects that I'm aware of is the traditional Object objname = new object(); – Tom Bennett Aug 17 '17 at 17:06
  • 1
    He hasn't created a new object, just [casted](https://stackoverflow.com/questions/5289393/casting-variables-in-java) the event source as the type of object that he knows it will be – Joel Manning Aug 17 '17 at 18:25