44

For example, I have a window with a preference button. I want to make it so that when user press the preference button and checks his/her appropriate options and press ok, it saves the preference, then when user presses run on the main window, it runs accordingly to preference the user changed on the preference window.

Thank you in advance.

js0823
  • 1,843
  • 8
  • 24
  • 36
  • Do you mean the behavior of the web page changes based upon preference? Save the preferences in a database table. – Tony Ennis Oct 25 '10 at 17:25

3 Answers3

101

You can use java.util.prefs package. A simple example:

// Retrieve the user preference node for the package com.mycompany
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);

// Preference key name
final String PREF_NAME = "name_of_preference";

// Set the value of the preference
String newValue = "a string";
prefs.put(PREF_NAME, newValue);

// Get the value of the preference;
// default value is returned if the preference does not exist
String defaultValue = "default string";
String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string"

There are many more examples at java2s.com.

Peter Knego
  • 79,991
  • 11
  • 123
  • 154
  • example depot link is dead. – harmanjd Dec 09 '12 at 23:12
  • 1
    I know this is a very old answer but hoping to get reply. I want to ask if I have 100+ setting data, does this will be best approach or there could be other like storing in file? – Aman Nov 01 '17 at 04:28
  • @Aman Do you really have 100+ setting data?This doesn't make much sense.But anyway.Preferences are used for storing small amount of data.100+ is okay though – Steve Moretz Sep 15 '19 at 10:15
10

There is a Java Preferences API specifically for this purpose. It lets you store per-user preferences in an easy cross-platform way, while the API itself takes care of where and how to store the data.

Arnaud P
  • 12,022
  • 7
  • 56
  • 67
casablanca
  • 69,683
  • 7
  • 133
  • 150
0
public void saveProperties() {
    try {            
        String USER_NAME = "Some name";
        String DP_ADDRESS = "Some url";
        //create a properties file
        Properties props = new Properties();
        props.setProperty("User name", USER_NAME);
        props.setProperty("Display picture address", DP_ADDRESS);
        File f = new File("YOUR_TARGET_FILE_PATH");
        OutputStream out = new FileOutputStream( f );
        //If you wish to make some comments 
        props.store(out, "User properties");
    }
    catch (Exception e ) {
        e.printStackTrace();
    }
}

You may use java.util.Properties to save your preferences

Rahul
  • 289
  • 2
  • 7
  • 2
    I know this is 2 years old, but not everyone uses a Microsoft Windows computer, and furthermore, the majority have `C:` set as their default drive, with **even fewer** having an `E:` drive installed. –  Dec 06 '17 at 01:11