2012-08-31 8 views
5

Sto facendo un'applicazione di elaborazione di testi per praticare Java e mi piacerebbe che quando l'utente tenta di chiudere l'applicazione, verrà visualizzato un JFrame che chiede di salvare le modifiche.setDefaultCloseOperation per mostrare una JFrame invece

Stavo pensando a setDefaultCloseOperation() ma finora ho avuto poca fortuna. Mi piacerebbe anche che appaia, se possibile, l'utente fa clic sulla "X" in alto a destra della finestra.

risposta

9

È possibile impostare JFrame DefaultCloseOperation su qualcosa come DO_NOTHING, quindi impostare WindowsListener per acquisire l'evento close e fare ciò che si desidera. Pubblicherò un esempio in pochi minuti.

EDIT: Ecco l'esempio:

public static void main(String[] args) { 
     final JFrame frame = new JFrame("Test Frame"); 

     frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 

     frame.setSize(800, 600); 

     frame.addWindowListener(new WindowAdapter() { 
      //I skipped unused callbacks for readability 

      @Override 
      public void windowClosing(WindowEvent e) { 
       if(JOptionPane.showConfirmDialog(frame, "Are you sure ?") == JOptionPane.OK_OPTION){ 
        frame.setVisible(false); 
        frame.dispose(); 
       } 
      } 
     }); 

     frame.setVisible(true); 
    } 
+0

1) ITYM 'frame.addWindowListener (nuova WindowAdapter() {' (altrimenti è un errore di compilazione) 2) La JRE non finirà in quanto l'EDT è ancora in esecuzione. Ecco una delle rare occasioni in cui la chiamata 'System.exit (0)' potrebbe essere necessaria. –

+0

@AndrewThompson quale suggeriresti di essere il modo più sicuro per chiudere un'applicazione invece di System.exit (0); ? – Andrei0427

+0

Bene, si potrebbe prima guardare i thread in esecuzione e controllare che sia ancora in esecuzione l'EDT. Se è così, sarebbe abbastanza sicuro chiudere la JVM usando 'System.exit (0)'. Ma c'è una soluzione migliore qui, vedere la mia risposta .. –

3
  • si deve aggiungere un WindowListener al JFrame.

  • All'interno del metodo windowClosing, è possibile fornire il codice richiesto.

Ad esempio:.

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class ClosingFrame extends JFrame { 

    private JMenuBar MenuBar = new JMenuBar(); 
    private JFrame frame = new JFrame(); 
    private static final long serialVersionUID = 1L; 
    private JMenu File = new JMenu("File"); 
    private JMenuItem Exit = new JMenuItem("Exit"); 

    public ClosingFrame() { 
     File.add(Exit); 
     MenuBar.add(File); 
     Exit.addActionListener(new ExitListener()); 
     WindowListener exitListener = new WindowAdapter() { 

      @Override 
      public void windowClosing(WindowEvent e) { 
       int confirm = JOptionPane.showOptionDialog(frame, 
         "Are You Sure to Close this Application?", 
         "Exit Confirmation", JOptionPane.YES_NO_OPTION, 
         JOptionPane.QUESTION_MESSAGE, null, null, null); 
       if (confirm == JOptionPane.OK_OPTION) { 
        System.exit(0); 
       } 
      } 
     }; 
     frame.addWindowListener(exitListener); 
     frame.setDefaultCloseOperation(EXIT_ON_CLOSE); 
     frame.setJMenuBar(MenuBar); 
     frame.setPreferredSize(new Dimension(400, 300)); 
     frame.setLocation(100, 100); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    private class ExitListener implements ActionListener { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      int confirm = JOptionPane.showOptionDialog(frame, 
        "Are You Sure to Close this Application?", 
        "Exit Confirmation", JOptionPane.YES_NO_OPTION, 
        JOptionPane.QUESTION_MESSAGE, null, null, null); 
      if (confirm == JOptionPane.OK_OPTION) { 
       System.exit(0); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       ClosingFrame cf = new ClosingFrame(); 
      } 
     }); 
    } 
} 
3
import java.awt.event.*; 
import javax.swing.*; 

public class QuickGuiTest { 

    public static void main(String[] args) { 
     Runnable r = new Runnable() { 
      @Override 
      public void run() { 
       final JFrame frame = new JFrame("Test Frame"); 

       frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 
       frame.setSize(600, 400); 
       frame.addWindowListener(new WindowAdapter() { 
        @Override 
        public void windowClosing(WindowEvent e) { 
         int result = JOptionPane.showConfirmDialog(
           frame, "Are you sure?"); 
         if(result==JOptionPane.OK_OPTION){ 
          // NOW we change it to dispose on close.. 
          frame.setDefaultCloseOperation(
            JFrame.DISPOSE_ON_CLOSE); 
          frame.setVisible(false); 
          frame.dispose(); 
         } 
        } 
       }); 
       frame.setVisible(true); 
      } 
     }; 
     SwingUtilities.invokeLater(r); 
    } 
}