2016-11-26 78 views
0

起初,我知道有很多关于“KeyListener不起作用”的威胁。问题是,我不知道为什么它不起作用,其他线程对我来说不是帮助... 如果用户按下“Shift”,程序应该关闭。KeyListener不起作用

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 

} 

}

+0

对不起不移位,*空间 –

+0

有一个编辑按钮靠近您帖子的底部。利用它来纠正帖子中的错误并添加任何相关的附加信息。你有任何错误?如果您添加调试,您是否看到您的密钥发布事件被称为? e.getKeyCode()的价值是什么? – scrappedcola

+0

如果您希望应用程序在用户按下SHIFT时退出,为什么要测试VK_SPACE? –

回答