简体   繁体   中英

Java method to return string from JTextField

There is a main method which have different textfields with the same KeyListener class

 textfield1.addKeyListener( new TextfieldKeyListener() );
 textfield2.addKeyListener( new TextfieldKeyListener() );
 textfield3.addKeyListener( new TextfieldKeyListener() );

The KeyListener class is something like this.

public class TextfieldKeyListener implements KeyListener
{

 public void keyTyped( KeyEvent e )
 {

  //This method should get a string from any given textfield.
  system.out.println(textfield.getText().toString() );
 }

}

Is it possible that a KeyListener class takes a string from a textfield and print it? One way is that three textfields should have three KeyListener classes but here should be one KeyListener class for all the textfields.

public class TextfieldKeyListener implements KeyListener {
    public void keyTyped(KeyEvent e) {
        Object src = e.getSource();
        if (src instanceof JTextField) {
            JTextField textField = (JTextField) src;
            System.out.println(textField.getText());
        }
    }
}

Refer to the javadoc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM