Java:了解偏好
Java: Understanding Preferences
所以我第一次开始使用Preferences
。例如:
JFrame frame = new JFrame("");
frame.addWindowListener(new WindowListener() {
@Override
public void windowClosing(WindowEvent e) {
pref.put("LAST_WIDTH", "" + frame.getWidth());
pref.put("LAST_HEIGHT", "" + frame.getHeight());
System.exit(0);
}
我在第一次启动应用程序时尝试检索最后一个尺寸时遇到问题。
if(pref.get("LAST_WIDTH", "") != null && pref.get("LAST_HEIGHT", "") != null){
try{
frame.setSize(Integer.parseInt(pref.get("LAST_WIDTH", "")), Integer.parseInt(pref.get("LAST_HEIGHT", "")));
} catch(NumberFormatException e){
frame.setSize(640, 480);
}
} else{
frame.setSize(640, 480);
}
是的,我找到了使用 try-catch 的解决方法,但我想了解首选项的工作原理。如果我第一次启动应用程序并尝试检索不应该存在的密钥,preferences return 是什么?
操作系统是 Windows7 如果重要的话。
您在您的示例中使用得很好!
String a = pref.get("key", "defaultValue");
Parameters:
key - key whose associated value is to be returned.
def - the value to be returned in the event that this preference node has no value associated with key.
所以在你的情况下,用你的默认值替换空字符串。
frame.setSize(Integer.parseInt(pref.get("LAST_WIDTH", "640")), Integer.parseInt(pref.get("LAST_HEIGHT", "480")));
所以我第一次开始使用Preferences
。例如:
JFrame frame = new JFrame("");
frame.addWindowListener(new WindowListener() {
@Override
public void windowClosing(WindowEvent e) {
pref.put("LAST_WIDTH", "" + frame.getWidth());
pref.put("LAST_HEIGHT", "" + frame.getHeight());
System.exit(0);
}
我在第一次启动应用程序时尝试检索最后一个尺寸时遇到问题。
if(pref.get("LAST_WIDTH", "") != null && pref.get("LAST_HEIGHT", "") != null){
try{
frame.setSize(Integer.parseInt(pref.get("LAST_WIDTH", "")), Integer.parseInt(pref.get("LAST_HEIGHT", "")));
} catch(NumberFormatException e){
frame.setSize(640, 480);
}
} else{
frame.setSize(640, 480);
}
是的,我找到了使用 try-catch 的解决方法,但我想了解首选项的工作原理。如果我第一次启动应用程序并尝试检索不应该存在的密钥,preferences return 是什么?
操作系统是 Windows7 如果重要的话。
您在您的示例中使用得很好!
String a = pref.get("key", "defaultValue");
Parameters:
key - key whose associated value is to be returned.
def - the value to be returned in the event that this preference node has no value associated with key.
所以在你的情况下,用你的默认值替换空字符串。
frame.setSize(Integer.parseInt(pref.get("LAST_WIDTH", "640")), Integer.parseInt(pref.get("LAST_HEIGHT", "480")));