Reputation: 59
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:
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.
Upvotes: 0
Views: 122
Reputation: 324118
KeyEvents are only dispatched to the component with focus. By default a JPanel is not focusable, so it will not receive KeyEvents.
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.
Upvotes: 1