Search code examples
javaswingjtextfieldkeylistenerkeyevent

getting source of KeyEvent


i have two text fields(tf1 and tf2) on which in have used KeyEvent to get the typed characters.

JTextField tf1 = new JTextField(10);
        JTextField tf2 = new JTextField(10);
        tf1.setFocusable(true);
        tf2.setFocusable(true);
        //regerstring for event
        tf1.addKeyListener(new KeyHandler(tf1, tf2));
        tf2.addKeyListener(new KeyHandler(tf1, tf2));








 class KeyHandler extends KeyAdapter{
    JTextField tf1;
    JTextField tf2;
    KeyHandler(JTextField tf1, JTextField tf2){
    tf1 = this.tf1;
    tf2 = this.tf2;
    }
    public void keyTyped(KeyEvent e){
    char ch = e.getKeyChar();
    System.out.println(e.getKeyLocation());

    if(e.getSource() == tf1)
        System.out.println("tf1");
    else if (e.getSource() == tf2)
    System.out.println("tf2");

    }

i have tried getSource() of KeyEvent class but it returns the object of JTextField , i has to diffrentiate between tf1 and tf2.

How can i get associated textfiled reference in keyTyped()


Solution

  • Compare the addresses as follows :

    if (e.getSource() == tf1) { 
       // Source is the first text field
    }
    

    As MadProgrammer pointed out use instance variables for textfields you need to use outside the creation scope (in your case tf1 and tf2)