[英]Java how do I save a background color once my application has been launched again
我正在尝试在游戏中创建一个按钮,其中背景颜色将从light_gray变为dark_gray。 但是,当应用程序重新启动时,我必须重新选择按钮以使颜色恢复为dark_gray。
重新启动应用程序时,我将如何保存颜色?
我的代码非常简单,只是按钮上的一个动作侦听器,它随后更改所选项目的bg颜色。
好的,我现在有机会允许它创建属性文件,但是人们不知道如何存储数据。 我见过人们有一些东西,例如'properties.setProperty(“ Favorite sport”,“ Football”);' 但是,人们怎么可能拥有它来存储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();
}
}
});
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);
}
}
要调用它,请使用类似:
public static void main(String[] args) {
System.out.println("Background: " + retrieveBackground());
storeBackground(Color.RED);
}
您可以将颜色作为int值存储在属性文件中,如下所示:
windowDark.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
getProperties().setProperty("color", Integer.toString(getColor().getRGB()));
}
});
将属性作为该按钮的窗口成员,放在应用程序的某个常规位置(甚至更好)中(或者更好的是具有main()的类),然后使用getProperties()
对其进行访问。
当您需要使用颜色时,解析字符串:
Color color = new Color(Integer.parseInt(getProperties().getProperty("color")));
不要在每次单击按钮时保存属性文件,而是在应用程序即将退出时保存属性文件:
mainWindow.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
mainWindow.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
try {
File file = new File("DarkTheme.properties");
FileOutputStream fileOut = new FileOutputStream(file);
getProperties().store(fileOut, "Dark theme background colour");
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
mainWindow.dispose();
}
}
});
一旦终止应用程序,将完成在内存中所做的更改。 如果要保留某些数据(在这种情况下为背景色),则需要将其存储在某个位置,例如文件,数据库等。对于简单的应用程序,将数据存储在文件中将是可行的。 为此,您需要:-当应用程序启动时,读取文件并应用文件中指定的颜色-在应用程序运行且用户更改颜色时,将颜色保存到同一文件中以处理文件,您将需要使用File,FileReader和FileWriter类(均在java.io包中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.