2017-08-08 66 views
-1

我試圖通過選擇菜單欄中的退出選項來退出我的應用程序,但我需要在程序關閉前收到提示。從JMenuItem獲取提示

我試圖通過閱讀類似的問題找到答案,但許多解決方案只是在menuItem的actionListener中以「System.exti(0)」結尾。在應用程序關閉之前,我需要獲得消息對話框。

在這裏,我已經宣佈了菜單欄,你可以看到的退出選項:

JMenuBar menuBar = new JMenuBar(); 
    JMenu archiveMenu = new JMenu("Archive"); 
    menuBar.add(archiveMenu); 
    newMap = archiveMenu.add("New Map"); 
    newMap.addActionListener(new ArchiveListener()); 
    loadPlaces = archiveMenu.add("Load Places"); 
    loadPlaces.addActionListener(new ArchiveListener()); 
    save = archiveMenu.add("Save"); 
    save.addActionListener(new ArchiveListener()); 
    exit = archiveMenu.add("Exit"); 
    exit.addActionListener(new ArchiveListener()); 

這裏是從ArchiveListener我的代碼。你可以看到,我試圖讓退出選項在非常底部的代碼工作,但這種解決方案不起作用:

class ArchiveListener implements ActionListener { 

    public void actionPerformed(ActionEvent ave) { 
     if (ave.getSource() == newMap) { 
      int result = fc.showOpenDialog(null); 
      if (result != JFileChooser.APPROVE_OPTION) { 
       return; 
      } else { 
       File file = fc.getSelectedFile(); 
       String filePath = file.getAbsolutePath(); 
       display.setImage(filePath); 
       validate(); 
       repaint(); 
      } 

     } else if (ave.getSource() == loadPlaces) { 

      int result = fc.showOpenDialog(null); 
      if (result != JFileChooser.APPROVE_OPTION) { 
       return; 
      } else { 
       loadPlaces(); 
      } 
     } 
     if (ave.getSource() == save) { 
      if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { 
       // File file = fc.getSelectedFile(); 
      } 
      try { 
       FileWriter outfile = new FileWriter("jarvafaltet.places.txt"); 
       PrintWriter out = new PrintWriter(outfile); 
       for (Place p : positionList.values()) { 
        System.out.println(p); 
        out.println(p); 
        out.close(); 
       } 

       outfile.close(); 

      } catch (FileNotFoundException e) { 
       JOptionPane.showMessageDialog(null, "Filen kan ej hittas"); 

      } catch (IOException e) { 
       JOptionPane.showMessageDialog(null, "Fel" + e.getMessage()); 

      } 

     } 

     if ("exit".equals(ave.getActionCommand())) { 

      int dialogButton = JOptionPane.YES_NO_OPTION; 
      JOptionPane.showConfirmDialog(null, "Would You Like to Save your Previous Note First?", "Warning", dialogButton); 

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

     } 

    } 

回答

1

你的代碼需要閱讀返回的值showConfirmDialog

int dialogButton = JOptionPane.showConfirmDialog(null, "Would You Like to Save your Previous Note First?", "Warning", JOptionPane.YES_NO_OPTION); 
if (dialogButton == JOptionPane.YES_OPTION) { 
    System.exit(NORMAL); 
} 

,你需要閱讀的javadoc:O)