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