【问题标题】:How to exit Application from JMenu item?如何从 JMenu 项中退出应用程序?
【发布时间】:2018-12-29 15:21:36
【问题描述】:

在 Jframe 中,我有一个菜单,在其中我有一个名为 Exit 的菜单项。我想要程序,所以当单击退出时应用程序退出。但在出现 JOptionPane 询问您是否要退出之前。我试过了,但它不起作用。

private void jExitActionPerformed(java.awt.event.ActionEvent evt) 
      {                                      

            String toExit = String.valueOf(jExit);


        if(jExit.equals(evt.getActionCommand())){

         int dialogButton = JOptionPane.YES_NO_OPTION;
         JOptionPane.showConfirmDialog (null, "Would You Like to Exit?","Warning",dialogButton);

         if(dialogButton == JOptionPane.YES_OPTION){
            System.exit(0);
         }

    }      
}   

【问题讨论】:

  • 欢迎来到 Stack Overflow!请使用tour,环顾四周,并通读help center,尤其是How do I ask a good question? 和What topics can I ask about here?。请添加完整的错误消息和Minimal, Complete, and Verifiable example。
  • 使用逻辑一致的形式缩进代码行和块。缩进是为了让代码的流程更容易理解!
  • @TimothyTruckle 没有错误消息。运行应用程序并单击菜单项中的退出时,没有任何反应。
  • 请发布 MCVE。
  • “这是我唯一的代码” 这不是一个完整的类定义,不包括导入或main(String[])。没有这些,它就不会运行。它甚至无法编译。

标签: java swing exit joptionpane jmenuitem


【解决方案1】:

试试我在下面展示的这些更改。基本上我已经将showConfirmDialod 方法的返回值设置为response 变量。并在if 条件中使用它。

private void jExitActionPerformed(java.awt.event.ActionEvent evt)
{
  String toExit = String.valueOf(jExit);

  if (jExit.equals(evt.getActionCommand()))
  {
    int dialogButton = JOptionPane.YES_NO_OPTION;
    int response = JOptionPane.showConfirmDialog(null, "Would You Like to Exit?", "Warning", dialogButton);

    if (response == JOptionPane.YES_OPTION)
    {
      System.exit(0);
    }
  }
}

【讨论】:

  • 我试过了,但也没有用。我花了一些时间安排并尝试了不同的方法,其中一种奏效了。我会发布答案。谢谢你
【解决方案2】:

这就是答案:

 private void jExitActionPerformed(java.awt.event.ActionEvent evt) {
     int response = JOptionPane.showConfirmDialog(this,"Do you want to Exit? ", 
     "Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);

     if (response == JOptionPane.YES_OPTION)
     {
        System.exit(0);
     } 
}  

【讨论】:

    猜你喜欢
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 2014-01-18
    • 1970-01-01
    • 2018-03-26
    • 2010-12-02
    • 1970-01-01
    相关资源
    最近更新 更多