Frage

SO I made a Java Program and there is a check box in my code. I want the check box variable saved for next startup on the JFrame application. I want the check box "Exit Launcher on Support" variable and the "Developer Console" to remember upon startup.

Code:

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);
    }
}

Please help...

War es hilfreich?

Lösung

you cannot do that without storing the value somewhere, this could be a file, or a database. The easiest would be to write to a file and then reading it back on startup.

You can use PrintWriter to write your data into a file and BufferedReader to read back. That's the easiest way to do it

    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);
    }

Andere Tipps

There are any number options available to you...

You Could...

Write to a file using Basic I/O. This gives you control over the format of the data, but requires a decent amount of code to store and retrieve the data, based how you want to format the data.

The solution is portable, in the fact that you can simply copy the configuration file whenever you move the application. It is also externally editable, this can be a good and bad thing

For example...

File configFile = new File("...");
String key = "checkBoxValue";
boolean value = true;
try (BufferedWriter bw = new BufferedWriter(new FileWriter(configFile))) {
    bw.write(key + "=" + Boolean.toString(value));
    bw.newLine();
} catch (IOException exp) {
    exp.printStackTrace();
}
try (BufferedReader br = new BufferedReader(new FileReader(configFile))) {
    String text = null;
    while ((text = br.readLine()) != null) {
        String[] parts = text.split("=");
        if (key.equals(parts[0])) {
            value = Boolean.parseBoolean(parts[1]);
        }
    }
} catch (IOException exp) {
    exp.printStackTrace();
}

You Could...

Use an XML based format and write the data to disk.

This, again, requires a decent amount of code to get working, but is reasonably flexible, as you can store structured data relatively easily and supports querying via the XPath API

The solution is portable, in the fact that you can simply copy the configuration file whenever you move the application. It is also externally editable, this can be a good and bad thing

For example...

// Writing...
try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    // Root Node
    Element configNode = doc.createElement("config");
    doc.appendChild(configNode);

    // Form node
    Element formNode = doc.createElement("form");
    configNode.appendChild(formNode);
    // Name of form
    formNode.setAttribute("name", "settingsForm");

    Element checkBoxDevConsole = doc.createElement("property");
    formNode.appendChild(checkBoxDevConsole);
    checkBoxDevConsole.setAttribute("name", "developerConsole");
    checkBoxDevConsole.setAttribute("type", "boolean");
    checkBoxDevConsole.setAttribute("value", Boolean.toString(chckbxDevoleperConsole.isSelected()));

    Element checkBoxExit = doc.createElement("property");
    formNode.appendChild(checkBoxExit);
    checkBoxExit.setAttribute("name", "exitSupport");
    checkBoxExit.setAttribute("type", "boolean");
    checkBoxExit.setAttribute("value", Boolean.toString(chckbxSupportexit.isSelected()));

    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.setOutputProperty(OutputKeys.INDENT, "yes");
    tf.setOutputProperty(OutputKeys.METHOD, "xml");
    tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("config.xml"));
    tf.transform(source, result);
} catch (ParserConfigurationException | TransformerException ex) {
    ex.printStackTrace();
}

// Reading...
try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new File("config.xml"));

    XPath xPath = XPathFactory.newInstance().newXPath();
    // Get developer console value...
    XPathExpression xExpress = xPath.compile("/config/form[@name='settingsForm']/property[@name='developerConsole']");
    Node devNode = (Node) xExpress.evaluate(doc, XPathConstants.NODE);
    boolean devConsole = Boolean.parseBoolean(devNode.getAttributes().getNamedItem("value").getNodeValue());

    xExpress = xPath.compile("/config/form[@name='settingsForm']/property[@name='exitSupport']");
    Node exitNode = (Node) xExpress.evaluate(doc, XPathConstants.NODE);
    boolean exitSupport = Boolean.parseBoolean(exitNode.getAttributes().getNamedItem("value").getNodeValue());
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) {
    ex.printStackTrace();
}

nb: The reading process demonstrated is very basic, as you should be checking to see if the results of the XPath query actually return a valid result and that the node actually contains a value attribute

You Could...

Use the Properties API, which is just a key/value pair (backed by a Map) which provides functionality for you to save and load it internally.

This is relatively easy to use, but still requires you to parse the resulting values, as they are simply maintained as String pairs.

The strength of this approach is that you can decide where the values are actually stored (this can also be a weakness when dealing with restrictive OS's like Windows 7/8)

The solution is portable, in the fact that you can simply copy the configuration file whenever you move the application. It is also externally editable, this can be a good and bad thing

For example...

// Writing
Properties properties = new Properties();
properties.put("settings.developerConsole", chckbxDevoleperConsole.isSelected());
properties.put("settings.supportExit", chckbxSupportexit.isSelected());

try (OutputStream os = new FileOutputStream(new File("config.properties"))) {
    properties.store(os, "Form settings");
} catch (IOException exp) {
    exp.printStackTrace();
}

// Reading...
Properties properties = new Properties();
try (InputStream is = new FileInputStream(new File("config.properties"))) {
    properties.load(is);
} catch (IOException exp) {
    exp.printStackTrace();
}

String setting = properties.getProperty("settings.developerConsole");
chckbxDevoleperConsole.setSelected(setting == null ? false : Boolean.parseBoolean(setting));
setting = properties.getProperty("settings.supportExit");
chckbxSupportexit.setSelected(setting == null ? false : Boolean.parseBoolean(setting));

You Could...

You could use the Preferences API. This API allows you to store data related to package/classes and store primitive values in such away that you don't need to worry about parsing the result between reads and writes.

The API is relatively simple to use, you simply get an instance of the Preferences object for the package/class you want to store data against and set/get the values you want. There's no need to read or write the content, as it's done automatically.

The only downside is you lose control over where the content is stored, as it's implementation specific. This means you want be able to simply crack a file open in your favorite editor and make modifications to it should you want, like the other options. Personally, for this one drawback, the API is my preferred method for storing user preferences.

Have a look here for examples

This solution is not portable (this is depended on the implementation of the Preferences API and the OS capabilities. For example, on Windows, the Preferences data is generally stored in the system registry. Unless you're using roaming profiles, the preferences are not easily portable across different systems).

For example...

// Writing...
Preferences pref = Preferences.userNodeForPackage(Settings.class);
pref.putBoolean("settings.developerConsole", chckbxDevoleperConsole.isSelected());
pref.putBoolean("settings.supportExit", chckbxSupportexit.isSelected());

// Reading...
Preferences pref = Preferences.userNodeForPackage(Settings.class);
chckbxDevoleperConsole.setSelected(pref.getBoolean("settings.developerConsole", false));
chckbxDevoleperConsole.setSelected(pref.getBoolean("settings.supportExit", false));

You Could...

Use a database of some kind, standalone or otherwise.

This is a lot of work for simply saving configuration, but, if you're already running a database of some kind to read/write application data, it's not a bad idea.

This solution is relatively portable, depending on the database. If done right, it would also be possible to change database solutions with little impact on the application, so you could go from a standalone database to a server database or visa-versa depending on your needs.

There are to concepts Object and Entity. Objects live in memory, when they are recollected from garbage collector they are destroyed forever. Entity is a Object that persist after application ends. So you need to persist checkbox's value somewhere, database, file,...

You could use serialization to save the state of the object to a file and load it when you launch your app.

Here is a simple example with a JCheckbox: http://java-demos.blogspot.ca/2012/10/using-serialization-on-jcheckbox.html

There is no way of doing it without storing the data somewhere.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top