0

I have been wondering about saving and loading jcheckbox and jtextfields values in Java. Is it possible to save and load jcheckbox and jtextfields values? I have attached the picture of a small program in which I would like to save the values of checkbox and load them to review later. Do I use JFileChooser to do the operation?

   public class Try extends JFrame {
   private JPanel contentPane;
   private JCheckBox chckbx_1;
private JCheckBox chckbx_2;
private JTextField textField;
private JTextField textField_1;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Try frame = new Try();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Try() {
    setTitle("Price tag");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    chckbx_1 = new JCheckBox("Price");
    chckbx_1.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if(e.getStateChange() == ItemEvent.SELECTED){
                textField.setEnabled(true);
                textField.setText("");
            }
            else if(e.getStateChange() == ItemEvent.DESELECTED){
                textField.setEnabled(false);
                textField.setText("");
        }
        }
    });

    chckbx_1.setBounds(72, 7, 81, 41);
    contentPane.add(chckbx_1);

    chckbx_2 = new JCheckBox("New Price");
    chckbx_2.addItemListener(new ItemListener() {
         @Override
        public void itemStateChanged(ItemEvent e) {
            if(e.getStateChange() == ItemEvent.SELECTED){
                textField.setEnabled(true);
                textField.setText("");
            }
            else if(e.getStateChange() == ItemEvent.DESELECTED){
                textField_1.setEnabled(false);
                textField_1.setText("");
        }
        }
    });
    chckbx_2.setBounds(72, 51, 89, 50);
    contentPane.add(chckbx_2);

    textField = new JTextField();
    textField.setBounds(196, 17, 86, 20);
    contentPane.add(textField);
    textField.setColumns(10);

    textField_1 = new JTextField();
    textField_1.setBounds(196, 66, 86, 20);
    contentPane.add(textField_1);
    textField_1.setColumns(10);

    JButton btn1 = new JButton("Save");
    btn1.setBounds(193, 173, 89, 23);
    contentPane.add(btn1);

    JButton btn2 = new JButton("Load");
    btn2.setBounds(314, 173, 89, 23);
    contentPane.add(btn2);
}}

enter image description here

Latif
  • 125
  • 1
  • 4
  • 16
  • 1
    save to a file ..read the file ?? read this http://www.codejava.net/coding/reading-and-writing-configuration-for-java-application-using-properties-class – Madhawa Priyashantha Sep 14 '15 at 10:27
  • do you want to save the jcheckbox value in a simple text file or u mean in database? – Jad Chahine Sep 14 '15 at 11:26
  • Create a model to back up your form and save it. – Stefan Sep 14 '15 at 12:40
  • did you check my answer? it should works – Jad Chahine Sep 15 '15 at 07:38
  • Thanks. Yes, I did. By looking at the website of codejava.net/coding/… I got have to save and load. But it can only save one file and load it. the problem is I can not save multiple files. Another question is that what if my jframe includes jtable under the checkbox and textfields. Can I save all the data I mean , the checkbox status, textfield as well as jtable vaues together. – Latif Sep 15 '15 at 07:47
  • Sorry Jad Chahine, I was going to send the comment to Fast Snail. Any way , Do you have any suggestions about the question above. I mean, if my jframe includes jtable under the checkbox and textfields. Can I save all the data I mean , the checkbox status, textfield as well as jtable vaues together. – Latif Sep 15 '15 at 08:01
  • if your jframe includes jtable , and other components you should use database and not simply text files, because the data became really huge and if you want to use files u can use it like the answer that i posted to you, you can save anything and retrieve it using theses predefined classes (printwriter,filewriter ...) – Jad Chahine Sep 15 '15 at 08:13
  • your question is "How to save and load checkBox states and text Field values in java?" and not how to save jtable data(it is another question) , so check my answer it should works for you and if it works mark it as accepted, good luck – Jad Chahine Sep 15 '15 at 08:23
  • Thnaks friend. Yes, it worked. Can i use it with JFileChooser do save multi files? – Latif Sep 15 '15 at 09:03
  • yes for sure u can, please check my answer, i edit it now – Jad Chahine Sep 15 '15 at 09:14
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/89656/discussion-between-laddie-and-jad-chahine). – Latif Sep 15 '15 at 09:21
  • Hi, Could you give a simple example to use sql to save data ? Example: My above application's data. – Latif Sep 15 '15 at 10:43
  • İs sql a program ? do I need to install it to insert data? – Latif Sep 15 '15 at 10:55
  • Here is my email: Latif0706@gmail.com I would be very appreciated if I coud any help – Latif Sep 15 '15 at 11:23

2 Answers2

2

The variables that you should use are :

 private FileWriter fw;
 private PrintWriter pw;
 private BufferedReader br;

For Saving the checkbox status and textfield value you can use FileWriter and PrintWriter to save in file:

btn1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String desktopPath = System.getProperty("user.home") + "/Desktop/";
                try {
                    fw = new FileWriter(desktopPath + "yourfile.txt");
                } catch (IOException ex) {
                    System.out.println("Error : " + ex);
                }
                pw = new PrintWriter(fw);
                pw.println(chckbx_1.isSelected() + "-" + textField.getText() + "-" + chckbx_2.isSelected()
                        + " -" + textField_1.getText());
                if (pw != null) {
                    pw.close();
                }
            }
        });

And for reading from the file you can use BufferedReader and use StringTokenizer for splitting the read line from the file :

btn2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String desktopPath = System.getProperty("user.home") + "/Desktop/";
                try {
                    String sCurrentLine;
                    br = new BufferedReader(new FileReader(desktopPath + "yourfile.txt"));
                    while ((sCurrentLine = br.readLine()) != null) {
                        StringTokenizer tokenizer = new StringTokenizer(sCurrentLine, "-");
                        if (tokenizer.hasMoreElements()) {
                             Boolean boolean1 = Boolean.valueOf(tokenizer.nextToken());
                             chckbx_1.setSelected(boolean1);
                        }
                        if (tokenizer.hasMoreElements()) {
                            textField.setText(tokenizer.nextToken());
                        }
                        if (tokenizer.hasMoreElements()) {
                             Boolean boolean1 = Boolean.valueOf(tokenizer.nextToken());
                             chckbx_2.setSelected(boolean1);
                        }
                        if (tokenizer.hasMoreElements()) {
                            textField_1.setText(tokenizer.nextToken());
                        }

                    }
                } catch (FileNotFoundException ex) {
                    System.out.println("Error : " + ex);
                } catch (IOException ex) {
                    System.out.println("Error : " + ex);
                }
            }
        });

And if you want to read from multi-file u can use JFileChooser like :

    btn2.addActionListener(new ActionListener() {
                @Override
                    public void actionPerformed(ActionEvent e) {
                        JFileChooser fc = new JFileChooser();
                        int ret = fc.showOpenDialog(null);
                        if (ret == JFileChooser.APPROVE_OPTION) {
                            File file = fc.getSelectedFile();
                             filename = file.getAbsolutePath();
                        }
....

and then, put the code for read:

br = new BufferedReader(new FileReader(filename));
Jad Chahine
  • 6,849
  • 8
  • 37
  • 59
1

You can make this by saving CheckBox selected index and text field to a file for example .txt and formating like

StateCheckBox1|2|StateTextField1|example

Then, when you read it you will take whole line and using .split() method, saving it to a String array.

Of course the better idea is to use Database, but if you want to save only few states, you no need to use it.

Otherwise if you are not closing you application, and want to load previous state of your's components, you can make Object for example. StateHolder which one hold your states.

If you want some more explanation about how to make this .txt just ask. I will try to explain it to you.

Thodgnir
  • 148
  • 1
  • 11