如何在Java中保存首选项用户设置?

问题描述:

例如,我有一个带有首选项按钮的窗口。
我想这样做,以便当用户按下首选项按钮并检查他/她的相应选项并按确定时,它会保存首选项,然后当用户按下主窗口上的运行时,它会相应地运行以优先于用户在偏好窗口中更改。

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.

提前谢谢。

您可以使用 java.util.prefs 包。一个简单的例子:

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"

还有更多 java2s.com上的示例