Search code examples
javaswingjtextfieldjcheckbox

How to save and load checkBox states and text Field values in java?


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


Solution

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