按任意键退出不正常

时间:2014-12-23 08:59:42

标签: java swing jframe keylistener

我写了以下代码,请检查一下:

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Example{
    public static void main(String[] args) {
        System.out.println("Hello StackOverflow");
        System.out.println("Press any key to exit");
       try{        
        getCh();        
        }
        catch(Exception e) {
         System.out.println("Error"+e);
        }

    }

    public static void getCh() {  
        final JFrame frame = new JFrame();  
        synchronized (frame) {  
            frame.setUndecorated(true);  
            frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);  
            frame.addKeyListener(new KeyListener() {
                public void keyPressed(KeyEvent e) {  
                    synchronized (frame) {  
                        frame.setVisible(false);  
                        frame.dispose();  
                        frame.notify();  
                    }  
                }  
                @Override 
                public void keyReleased(KeyEvent e) {  
                }  
                @Override 
                public void keyTyped(KeyEvent e) {  
                }  
            });  
            frame.setVisible(true);  
            try {  
                frame.wait();  
            } catch (InterruptedException e1) {  
            }  
        }  
    }
}

部分工作,但工作不正常。我需要在打印 Hello StackOverflow 后退出任何按键。请指导我们。我需要一个简单的程序。这段代码看起来很冗长,并且有很多重组件,比如Swing。请帮帮我们!!

1 个答案:

答案 0 :(得分:0)

试试这个

public class Example {

    public static void main(String[] args) {

        System.out.println("Hello StackOverflow");
        System.out.println("Press any key to exit");

        Scanner scanner = new Scanner(System.in);
        int input = scanner.nextInt();
        System.exit(0);
    }
}