Hello,

The following custom class has compiler errors where it is not recognizing KeyListener.
Any idea on why I am getting this error?

import java.util.concurrent.*;
import java.util.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class worker1 extends Thread {

   private SynchronousQueue<Object> q;
	private int i;


   public worker1(SynchronousQueue<Object> q) {
       super("Worker 1");
       this.q = q;
       setFocusable(true);
       addKeyListener(
            new KeyAdapter()
            {
                public void keyTyped(KeyEvent event)
                {
                   i++;

                }
            }
       );
   }

   public void run() {
       try {

           while(i <= 10) {
                System.out.println ( i + "   " +  Thread.currentThread().getName());
           }


           q.put(new Object());

           q.take();


           for(int i =1001; i <= 2000; ++i) {
                System.out.println ( i + "   " +  Thread.currentThread().getName());
           }


           q.put(new Object());
       } catch (InterruptedException e) {

       }
   }

}

Thank you!

These are not methods of Thread.

setFocusable(true);
addKeyListener()

Edited 5 Years Ago by Ezzaral: n/a

Hello Guys,

Ezzaral - Would it be fine if I added the KeyListener in a non-thread Custom Class?

Jon - The compiler error is, "cannot find symbol - method addKeyListener(<anonymous.java.awt.event.KeyAdapter>)

Kindly let me know.

Thank you!

Ezzaral is right. What it's telling you is, this class doesn't have this method. I should have seen that right away. If you think about it, a Thread is not the sort of thing that takes input - it doesn't interact with the user. A graphics component that can take focus - that's an object can you can put a keylistener on. But I'm not sure what it would mean to hang a keylistener on a Thread... it almost sounds like putting an air conditioner on a happy thought.

This article has been dead for over six months. Start a new discussion instead.