所以我制作了一个Java程序,并且我的代码中有一个复选框。我希望保存复选框变量以供 JFrame 应用程序下次启动。 我希望在启动时记住“退出启动器支持”变量和“开发人员控制台”复选框。
代码:
import javax.swing.JFrame;
public class Settings {
/**
* @wbp.parser.entryPoint
*/
static void appSettings() {
JFrame settingsApp = new JFrame();
settingsApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
settingsApp.setAlwaysOnTop(true);
settingsApp.setResizable(false);
settingsApp.setVisible(true);
settingsApp.setTitle("Launcher Settings");
settingsApp.setSize(350, 500);
settingsApp.getContentPane().setLayout(new GridLayout(1, 0, 0, 0));
JPanel panel = new JPanel();
settingsApp.getContentPane().add(panel);
SpringLayout sl_panel = new SpringLayout();
panel.setLayout(sl_panel);
JLabel lblInfo = new JLabel("This is the settings window for the DevCity13 Launcher.");
sl_panel.putConstraint(SpringLayout.NORTH, lblInfo, 10, SpringLayout.NORTH, panel);
sl_panel.putConstraint(SpringLayout.WEST, lblInfo, 10, SpringLayout.WEST, panel);
panel.add(lblInfo);
JCheckBox chckbxDevoleperConsole = new JCheckBox("Devoleper Console");
chckbxDevoleperConsole.setToolTipText("Activate the devoleper console for error/glitch checking.");
chckbxDevoleperConsole.setEnabled(false);
sl_panel.putConstraint(SpringLayout.NORTH, chckbxDevoleperConsole, 6, SpringLayout.SOUTH, lblInfo);
sl_panel.putConstraint(SpringLayout.WEST, chckbxDevoleperConsole, 10, SpringLayout.WEST, panel);
panel.add(chckbxDevoleperConsole);
JCheckBox chckbxSupportexit = new JCheckBox("Exit Launcher under Support");
chckbxSupportexit.setToolTipText("Close the Launcher Window when Support button is pressed.");
sl_panel.putConstraint(SpringLayout.NORTH, chckbxSupportexit, 6, SpringLayout.SOUTH, chckbxDevoleperConsole);
sl_panel.putConstraint(SpringLayout.WEST, chckbxSupportexit, 10, SpringLayout.WEST, panel);
panel.add(chckbxSupportexit);
}
}
请帮忙...
最佳答案
如果不将值存储在某个地方,您就无法做到这一点,这可能是一个文件,也可能是一个数据库。最简单的方法是写入文件,然后在启动时读回它。
您可以使用 PrintWriter 将数据写入文件,并使用 BufferedReader 读回。这是最简单的方法
boolean storedExitLauncher;
boolean storedDevConsole;
try {
File dataContiner = new File("data.dat");
BufferedReader bufferedReader = new BufferedReader(new FileReader(dataContiner));
storedExitLauncher = Boolean.parseBoolean(bufferedReader.readLine());
storedDevConsole = Boolean.parseBoolean(bufferedReader.readLine());
} catch (FileNotFoundException e) {
storedDevConsole = storedExitLauncher = false;
} catch (IOException e) {
throw new RuntimeException(e);
}
//do your stuff here
boolean exitLauncher = false; //save the checkbox data
boolean devConsole = false; //save checkbox data
try {
PrintWriter printWriter = new PrintWriter("data.dat", "UTF-8");
printWriter.println(exitLauncher);
printWriter.println(devConsole);
} catch (FileNotFoundException e) {
throw new RuntimeException("Cannot save data, it will be lost");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
关于java - 在 JFrame 中保存复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22181873/