简体   繁体   中英

Creating a class that extends keyListener

In my java project, I want to check the input in each JTextField in a few different classes (with the exact same code)..

Right now I have the same code copied over and over and I was suggested with 2 options:

  1. Create a method and call the method instead.

  2. Create a new class that extends from another class (I don't know which yet) that has the method needed.

The code I'm using now is:

totalAmount.addKeyListener(new KeyAdapter() {
@Override
    public void keyTyped(KeyEvent arg0) {
    //do something
    }
});

And the new class is:

public class Listener extends KeyAdapter {
    public void keyTyped(KeyEvent arg0){
    //do something
    }
}

The problem is that I don't know if I'm extending the right class, and how to use the new class I've written...

Thanks in advance!

To do what you are wanting with your key adapter you would use

totalAmount.addKeyListener(new Listener());

and your code of your key adapter is correct.

public class Listener extends KeyAdapter {
    public void keyTyped(KeyEvent arg0){
        //do something
    }
}

To get the text from a JTextField you could either use this code inside your keyAdapter

System.out.println(totalAmount);

or, preferably you could use a document listener. This would be done by

public class documentListener implements DocumentListener //This is a listener
{
    public void changedUpdate(DocumentEvent e){

    }

    public void removeUpdate(DocumentEvent e){
        int lengthMe = e.getDocument().getLength();
        System.out.println(e.getDocument().getText(0,lengthMe));
    }

    public void insertUpdate(DocumentEvent e){
        int lengthMe = e.getDocument().getLength();
        System.out.println(e.getDocument().getText(0,lengthMe));
    }
}

and it would be added to the JTextField with

totalAmount.getDocument().addDocumentListener(new documentListener());

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