[英]KeyEvent never fires (java Swing)
at this moment I'm trying to add to my project Keyboard support and i have wird problem. 目前,我正在尝试向我的项目添加键盘支持,但是我遇到了麻烦的问题。 My listener doesn't catch any events.
我的听众没有捕获任何事件。 I did simple prints in code but nothing happends.
我用代码做了简单的打印,但是什么也没发生。 I've never had such problem before.
我从来没有遇到过这样的问题。
This is my class GUI: 这是我的类GUI:
public class GUI extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private ComponentAbstract korzen;
private GUI self;
public GUI() {
self=this;
this.stworz_PanelLogowania();
this.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("typed");
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("pressed");
}
});
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
korzen.tryClick(e.getX(), e.getY());
repaint();
}
});
this.repaint();
}
@Override
protected void paintComponent(Graphics g ) {
super.paintComponent(g);
korzen.repaint();
System.out.println("omatko");
korzen.draw((Graphics2D)g);
}
private void zmien_panel(ComponentAbstract newkorzen){
korzen=newkorzen;
self.repaint();
}
private void stworz_PanelLogowania(){
LinearPanel lp=new LinearPanel(220, 50, 300, 300);
//lp.setOrientarion(Orientation.VERTICAL);
lp.addComponent(new Label(0, 0, 350, 40, "Witamy w castorama APP"));
lp.setPadding(2);
lp.addComponent(new TextBox(0, 0, 350, 40));
korzen=lp;
System.out.println("kuniec");
}
}
What is interesting Mouse listener works perfect. 有趣的是,鼠标侦听器可以完美工作。 Edit: Before there was KeyAdapter but the result was the same.
编辑:之前有KeyAdapter,但结果是相同的。
KeyEvents are only dispatched to the component with focus. KeyEvent仅分派给具有焦点的组件。 By default a JPanel is not focusable, so it will not receive KeyEvents.
默认情况下,JPanel不能聚焦,因此它不会接收KeyEvent。
In the constructor you need to use: 在构造函数中,您需要使用:
setFocusable(true);
Then depending on the rest of your application the panel can now receive focus when you tab to the panel. 然后,根据应用程序的其余部分,当您轻触面板时,该面板现在可以接收焦点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.