M. Schwarze M. Schwarze - 8 days ago 7
Java Question

KeyListener does't work

At first, I know there are a lot of threats about "KeyListener doesn't work". The problem is, i don't know why it doesn't work and the other threads aren't a help for me...
The program should close if the user press "Shift".

public class Main extends JFrame implements KeyListener{

public static void main(String[] args){
new Main();
}

public Main(){
JFrame guiFrame = new JFrame();

//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
guiFrame.setLayout(new FlowLayout());
guiFrame.setTitle("");
guiFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
guiFrame.setUndecorated(true);
guiFrame.setAlwaysOnTop(true);
guiFrame.getContentPane().setBackground(Color.black);


JLabel jb1 = new JLabel("WER DAS LIEST IST BLÖD",JLabel.CENTER);
jb1.setFont(new Font("Serif", Font.BOLD, 140));
jb1.setForeground(Color.WHITE);
jb1.setLocation((guiFrame.getWidth()-jb1.getWidth())/2,50);


guiFrame.add(jb1);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
guiFrame.setVisible(true);
}

@Override
public void keyPressed(KeyEvent e) {

}

@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE){
System.exit(0);
}

}

@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}


}

Answer

Just implementing the KeyListener interface is not enough - you need to add it to some component (in your case the JFrame).

Try something like

guiFrame.addKeyListener(this);

See here for the API: http://docs.oracle.com/javase/8/docs/api/java/awt/Component.html#addKeyListener-java.awt.event.KeyListener-

And here for a the official tutorial: https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

Comments