【问题标题】:How to terminate program? [closed]如何终止程序? [关闭]
【发布时间】:2013-05-26 07:22:53
【问题描述】:

当按下“ESCAPE”时,如何让 Java 程序自行终止?我试过这个:

   public class Main {

   public static final int i = 12;

   public static void Exit(KeyEvent e) {

    if (e.getKeyCode() == 27)
    {
        System.exit(0);
    System.out.println("Closing");
    }

}

public static void main (String args[]) {

    while(i <= 0) {
        Exit(null);
    }

   }
}

但是,它似乎不起作用。有什么建议吗?

【问题讨论】:

标签: java


【解决方案1】:
while(i <= 0) {
    ...
}

并且 i 被初始化为 12。这将永远不会进入循环,除非你将 i 值更改为小于或等于 0 的值。

【讨论】:

    【解决方案2】:

    一些选项:

    • 使用System.exit(0)
    • 所有非守护线程都已完成。

    如果这是一个摇摆应用程序,则使用键绑定而不是键侦听器,并且您可以依赖 JFrame 的 X 按钮来终止应用程序(您可以使用 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE))。

    【讨论】:

    • 我实际上不能使用它,因为当程序启动时,由于程序不断循环,所有按钮都变得“不可按下”。这就是为什么我需要一个键来关闭程序。
    【解决方案3】:

    我只能找出两种截取 java 中的键的方法。

      1234563然后您可以在 java 中加载 dll 来帮助您满足您的要求。
    1. 如果您正在编写基于 SWING 的 GUI,那么您可以将 keypress lisenter 添加到您的组件中。您可能必须递归地将其添加到所有组件中才能在 UI 的任何级别拦截密钥。这是一个示例代码:

    使用方法向组件及其子组件添加键监听器:

    private void addKeyAndContainerListenerRecursively(Component c)
         {
    //Add KeyListener to the Component passed as an argument
              c.addKeyListener(this);
    //Check if the Component is a Container
              if(c instanceof Container) {
    //Component c is a Container. The following cast is safe.
                   Container cont = (Container)c;
    //Add ContainerListener to the Container.
                   cont.addContainerListener(this);
    //Get the Container's array of children Components.
                   Component[] children = cont.getComponents();
    //For every child repeat the above operation.
                   for(int i = 0; i < children.length; i++){
                        addKeyAndContainerListenerRecursively(children[i]);
                   }
              }
         }
    

    获取按键事件的方法:

      public void keyPressed(KeyEvent e)
         {
              int code = e.getKeyCode();
              if(code == KeyEvent.VK_ESCAPE){
    //Key pressed is the Escape key. Hide this Dialog.
                   setVisible(false);
              }
              else if(code == KeyEvent.VK_ENTER){
    //Key pressed is the Enter key. Redefine performEnterAction() in subclasses 
    to respond to pressing the Enter key.
                   performEnterAction(e);
              }
    //Insert code to process other keys here
         }
    

    希望对你有帮助!

    【讨论】:

    • 我尝试使用它,但我得到了 NullPointerException。我最初有一个“退出”按钮来终止程序,但是一旦用户按下“开始”按钮,它就会进入一个无限循环,这会导致“开始”按钮不断被按下,使用户无法使用红色“X”按钮或“退出”按钮。但是,由于循环位于按钮的 ActionListener 中,我无法使用 KeyEvent。我不是最新的编程,但我肯定在学习并且还有很多事情要做。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 2021-07-07
    • 2016-08-01
    • 2020-09-19
    • 1970-01-01
    相关资源
    最近更新 更多