如何给一个window类的对象添加键盘监听器?
Window y=new Window(this);
MousePolice police=new MousePolice();
y.setSize(1380, 770);//设置大小
Timer time=new Timer();//新建计时器
Mytask task=new Mytask();//新建计时器任务
task.setFrame(y,1380,750);//和任务中的容器连接
time.schedule(task, 0,20);//每0.2秒钟执行一次任务
y.setAlwaysOnTop(true);//一直在上
y.setVisible(true);//可见
y.addMouseListener(police);
addKeyListener(police);
y.addKeyListener(police);
这是主类里面的部分内容
class MousePolice implements MouseListener,KeyListener{
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ESCAPE||e.getKeyCode()==KeyEvent.VK_ENTER)
System.exit(0);
}
public void keyReleased(KeyEvent e) {}
}
这是监听器的类里面的内容,为什么按下Enter和ESC不能退出程序?
------解决方案--------------------
由于没有你的全部代码,推测是你的addKeyListener没有explicit parameter,你改为y.addKeyListener试一下看看。我的代码中是有响应的,你可以对比一下,代码如下:
Java code
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class KeyListenerTest
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(200, 200);
frame.setVisible(true);
frame.addKeyListener(new KeyListener()
{
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode() == KeyEvent.VK_ENTER)
System.exit(0);
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
});
}
}