1 Attachment(s)
Help: adding keylistener to a thread
Hi everyone, I'm working on a simple Java applet program. By default, the program will let a rectangle move from left to right in a continuous process. I implemented this feature by using a thread. What I want to do is: when the rectangle is moving from left to right, the program can receive the keyboard input and change the variable "active" and then let the rectangle change its moving direction to from up to down. My problem is I don't know how to add the keylistener to the program. Below (also attachment) is the existing code. Thanks in advance for your help!
Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
*
*
*/
public class TestJPanel extends JPanel implements Runnable{
private boolean active;
private Rectangle rect;
public TestJPanel()
{
super();
this.rect = new Rectangle( 100, 100, 50, 100);
this.active = false;
this.setFocusable( true);
return;
}
@Override
public void paint( Graphics g)
{
super.paint(g);
g.drawRect( this.rect.x, this.rect.y, this.rect.width, this.rect.height);
return;
}
public void start()
{
Thread thread = new Thread( this);
thread.start();
}
@Override
public void run()
{
for (int i = 0; i < 100; i++) {
this.move();
this.repaint();
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void move()
{
if( this.active == false)
this.rect.setLocation( this.rect.x + 2, this.rect.y);
else
this.rect.setLocation( this.rect.x, this.rect.y + 2);
return;
}
}