1 java swing colors jframe actionlistener
我正在尝试在游戏中创建一个按钮,背景颜色将从light_gray变为dark_gray.但是,当应用程序重新启动时,我必须重新选择按钮以将颜色恢复为dark_gray.
如何在重新启动应用程序时保存颜色?
我的代码非常简单,只是按钮上的动作监听器,然后更改所选项目的bg颜色.
好吧,我现在有机会允许它创建属性文件,但是人们不知道如何存储数据.我见过人们有像'property.setProperty("最喜欢的运动","足球")这样的东西;' 但是怎么能有这个以便它存储bg颜色?
windowDark.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
try {
Properties properties = new Properties();
properties.setProperty();
File file = new File("DarkTheme.properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, "Dark theme background colour");
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
Run Code Online (Sandbox Code Playgroud)
该java.util.prefs选项API非常适合用于存储在桌面上运行用户应用持久偏好数据.
以下是如何使用它来存储和检索持久背景颜色设置的示例:
import java.awt.Color;
import java.util.prefs.Preferences;
public class MyPrefs {
private static Preferences preferences =
Preferences.userRoot().node("myappname.ColorPreferences");
public static void storeBackground(Color background) {
preferences.putInt("background", background.getRGB());
}
public static Color retrieveBackground() {
// Second argument is the default when the setting has not been stored yet
int color = preferences.getInt("background", Color.WHITE.getRGB());
return new Color(color);
}
}
Run Code Online (Sandbox Code Playgroud)
要调用它,请使用以下内容:
public static void main(String[] args) {
System.out.println("Background: " + retrieveBackground());
storeBackground(Color.RED);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1249 次 |
| 最近记录: |