Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save application options before exit?

I have made an application and i need to save some options before exit.(something like window dimension, ..., that will be written in a file.)

The main frame has set this:

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

How can I save options that interests me?(before exiting of course)

Thanks!

like image 565
artaxerxe Avatar asked Mar 02 '10 07:03

artaxerxe


3 Answers

If you just want to do something when the application is shutting down, you can hook the shutdown using this code:

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {          public void run() {             // Do what you want when the application is stopping         }     })); 

However, this will not allow you to not close your window. If you need to check something before really exiting, you can override the windowClosing event:

addWindowListener(new WindowAdapter() {     public void windowClosing(WindowEvent e) {         // Do what you want when the window is closing.     } }); 

Note that the first solution - using the shutdown hook - has the advantage that it is not related to a window event, and will be executed even if the application is stopped by another event (except, of course, if the Java process is killed brutally).

like image 159
Romain Linsolas Avatar answered Sep 18 '22 14:09

Romain Linsolas


May be the following will help.

  1. First u need to read your property file. See doc

    Properties properties = new Properties(); try {   properties.load(new FileInputStream("filename.properties")); } catch (IOException e) {   System.err.println("Ooops!"); } 
  2. Second add event handler to your window, which will save your data in property file.All that you need to save just put in properties instance and store it on exit

     addWindowListener(new WindowAdapter() {   public void windowClosing(WindowEvent e) {     try {      properties.store(new FileOutputStream("filename.properties"), null);     } catch (IOException e) {     }   } }); 

That's all, if I'd understood you correct)

like image 45
ponkin Avatar answered Sep 16 '22 14:09

ponkin


You may register a WindowListener and save your options in the windowClose method.

And of course

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
like image 32
PeterMmm Avatar answered Sep 18 '22 14:09

PeterMmm