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!

Recommended Answers

All 5 Replies

Can you post the compiler output? It'd help if I could see what errors I'm looking for.

These are not methods of Thread.

setFocusable(true);
addKeyListener()

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.

Hello Jon,

Makes sense. Thank you!

Regards

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.