在我的 Java 应用程序中,我希望在应用程序启动时立即获取许多已保存的值和设置。所有这些值都应该存储在一个单例中。 例如,我有一个 JDialog,我在其中使用以下命令保存文件的路径:
AppSingleton appSingleton = AppSingleton.getInstance( );
private Preferences prefs;
private void btnSetPanelSetNavdataActionPerformed(java.awt.event.ActionEvent evt) {
appSingleton.setNavdataPath(txtNavdataPath.getText());
prefs = Preferences.userRoot().node(this.getClass().getName());
prefs.put("NAVDATA_PATH", txtNavdataPath.getText());
dispose();
}
我正在检查并且该值已保存。
这是我的单例:
public class AppSingleton
{
private static AppSingleton instance = null;
private String navdataPath = "";
private AppSingleton()
{
}
public static AppSingleton getInstance()
{
if(instance == null)
{
instance = new AppSingleton();
}
return instance;
}
public String getNavdataPath() {
return navdataPath;
}
public void setNavdataPath(String navdataPath) {
this.navdataPath = navdataPath;
}
public void initDefaultValues()
{
Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
this.navdataPath = prefs.get("NAVDATA_PATH","");
System.out.printf("CHECK DEFAULT: %s",this.navdataPath);
}
}
我试图从初始化 JFrame 的类中的 main() 方法获取保存的值:
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run() {
new IGAMainFrame().setVisible(true);
/* HERE!!! */
AppSingleton appSingleton = AppSingleton.getInstance();
appSingleton.initDefaultValues();
}
});
}
但是这些值不是从 Preference 类初始化的。 “CHECK DEFAULT”显示空字符串。我不明白为什么以及是否有更好的做法来在 GUI 应用程序启动时恢复所有保存的值。
谢谢!
最佳答案
将 btnSetPanelSetNavdataActionPerformed
内的行 prefs = Preferences.userRoot().node(this.getClass().getName());
更改为 prefs = Preferences .userRoot().node(Appsingleton.class.getName());
按钮单击方法内部,this.getClass()
不是 AppSingleton
关于Java:当 GUI 应用程序启动时,保存的首选项设置不会恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39029523/