【问题标题】:press any key exit not working properly按任意键退出无法正常工作
【发布时间】:2014-12-23 08:59:42
【问题描述】:

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

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。请大家帮忙!!

【问题讨论】:

  • 我认为你可以使用System.exit(0)
  • @Mayank 它不会对此做出任何改变!!

标签: java swing jframe keylistener


【解决方案1】:

试试这个

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);
    }
}

【讨论】:

  • 为什么是nextInt?你的意思是scanner 而不是ItemSelect
  • scanner 是一个对象,你可以随意命名
  • 谢谢,帽子!你只是在没有声明的地方得到ItemSelect
  • @Mayank ItemSelect 找不到符号,应该导入!!
  • @Mayank 不起作用!!如上所述出现错误@@
猜你喜欢
  • 1970-01-01
  • 2012-08-06
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 2017-08-05
  • 2014-12-21
  • 1970-01-01
相关资源
最近更新 更多