I don't know why KeyListener doesn't work. 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
}
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.