0
我正在用java测试我的keyListener。为什么我的java KeyListener不适用于我的ubuntu?
我的系统在Ubuntu 14.04。我在main中设置一个面板并初始化关键监听器。我还将focusable设置为true,并执行requestFocusInWindow。
但是当我运行该程序时,println从不出现在控制台中。对此感到困惑。
package key;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Key extends JPanel{
public void action(){
KeyListener k = new KeyListener(){
@Override
public void keyPressed(KeyEvent k){
System.out.println("key is pressed!");
}
@Override
public void keyReleased(KeyEvent e){
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e){
System.out.println("key is typed!");
}
};
this.addKeyListener(k);
this.setFocusable(true);
this.requestFocusInWindow();
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setSize(400,300);
JPanel panel = new JPanel();
panel.setBackground(Color.BLUE);
frame.add(panel);
frame.setVisible(true);
Key k = new Key();
k.action();
}
}
一个'KeyListener' ,严重的是,这件事情是如此脾气暴躁,仅仅使用[Key Bindings API](http://docs.oracl e.com/javase/tutorial/uiswing/misc/keybinding.html)解决了焦点相关的问题,并提示更好的代码重用和抽象 – MadProgrammer
我也希望'Key'实际上被添加到框架的某个点并使框架可见 – MadProgrammer
这是一个常见问题,使用相同的解决方案,[示例](http://stackoverflow.com/questions/16409352/keylistener-not-working/16409362#16409362),[exmaple]( http://stackoverflow.com/questions/21368475/keylistener-not-working-using-applet/21370349#21370349),[exmaple](http://stackoverflow.com/questions/16028573/keylistener-is-not-working/16028698#16028698),[示例](http://stackoverflow.com/questions/18029136/keylistener-not-working-requestfocus-not-fixing-it/18029321#18029321),[示例](http:// stackoverflow /我的问题/ 27270284/keylistener-is-not-working-in-java/27270454#27270454) – MadProgrammer