Search code examples
javaswingactionlistenerjtextfieldkeylistener

What is the proper use of KeyListener?


So I have been working on trying to extract the data in my jTextFields and this error message keeps popping up referring to an:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: calcu.turkey (<--my class) cannot be cast to java.awt.event.KeyListener

      jTextField2.addKeyListener(new java.awt.event.KeyListener() {

        @Override
        public void keyTyped(KeyEvent ke) {
            //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyPressed(KeyEvent ke) {
          //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyReleased(KeyEvent ke) {
            //To change body of generated methods, choose Tools | Templates.
        }
    });
    jTextField2.addKeyListener((KeyListener) this);
    jTextField2.setFont(new java.awt.Font("Times New Roman", 0, 10)); // NOI18N
    jTextField2.setText("0");
    getContentPane().add(jTextField2);
    jTextField2.setBounds(250, 40, 70, 20);

Most importantly this line: jTextField2.addKeyListener((KeyListener) this); as it views the (KeyListener) as an error. I was wondering how do you properly add the KeyListener so it grab the number in the textfield.


Solution

  • You don't use a KeyListener. Rarely do you have a need to do this. There are better API's to be used.

    For example when using a text component you would probably use a DocumentListener (see How to Write a Document Listener) or DocumentFilter (see Implementing a Document Filter).

    I was wondering how do you properly add the KeyListener so it grab the number in the textfield.

    Normally you would grab the number on some unrelated event. For example you have a "Submit" button on a form. Then in that case you would add an ActionListener to the button and then use the getText() method of the text field when you want to submit the form.

    Also, the Swing tutorial that I referenced above has a section on How to Write a Key Listener.