如何从JMenu项目退出Application?

时间:2018-12-29 15:21:36

标签: java swing exit joptionpane jmenuitem

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

    }      
}   

2 个答案:

答案 0 :(得分:0)

尝试下面显示的这些更改。基本上,我已经将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);
    }
  }
}

答案 1 :(得分:0)

这是答案:

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