Results 1 to 7 of 7
Like Tree1Likes
  • 1 Post By florachu2121

Thread: GUI: How to save these data to a text/dat file?

  1. #1
    florachu2121 is offline Member
    Join Date
    Jul 2010
    Location
    ASIA
    Posts
    3
    Rep Power
    0

    Question GUI: How to save these data to a text/dat file?

    Hello, this is my first time in java forums :)
    Here is my code which is slightly finished...i spent 2 weeks continuing this and still no progress :(
    I HAVE NO IDEA HOW TO SAVE THE DATA TO A TEXT FILE :'(
    i dont even know where to put it.
    im familiar with BufferedWriter, PrintWriter, etc.
    and i know how to use them, but NOT in GUI.
    the goal of my program is to add student data from the user, enable the user to edit, delete, sort and save.
    I can add, edit and delete only. Right now, i dont care how can i sort the students data, all i wanna know ryt now is how can i save the data to a file...

    My Teacher's Instruction:
    Save.
    Activating this button saves the current content of the course (together with the list of
    students) under the filename output.dat (object file).
    *** Store all successful transactions within a text file named log.txt ***
    :confused:


    Hope i can get some help :) i only got 1 and half days left for our defense
    Here is my code:
    Attached Files Attached Files
    Hazem Bavo likes this.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    If you can use println() to display the data you want to save,
    using the same logic, replace the class that prints to the screen with a class that writes to a disk file.
    Use Search on this forum for lots of code examples of how to write to a disk file.

    The GUI bit is to allow the user to specify when something is to be done.
    Have the listener either write out the records itself
    Or better, have the listener start a thread to write out the records.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    I'm not sure that the teacher is asking you to save the data in a text file as it looks to me as if he/she is giving you two instructions:
    1)
    – Activating this button saves the current content of the course (together with the list of students) under the filename output.dat (object file).
    and
    2)
    Store all successful transactions within a text file named log.txt
    So my interpretation suggests that output.dat is a file that contains your persisting data, and that since it should be an "object" file, the data should be serialized, and log.txt is a separate text file that contains information about "all successful transactions", whatever this means.

    I again recommend saving your information by serializing it, perhaps by extracting the data vector held by the JTable's table model. To that end, I'd recommend working directly with your JTable's model perhaps with a DefaultTableModel object. You also might want to subdivide your class into constituent GUI and a non-GUI classes.

    For the benefit of all, let me repost your code in the forum itself so that it is easily visible to all:

    Java Code:
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    
    public class MainGUI extends JFrame {
       // Declare variables:
       // array lists
       String[] columnNames = {"GENDER", "NAME", "COURSE", "YEAR", "ID"};
       Object[][] data = new Object[25][5];
    
       // table
       JTable table = new JTable(data, columnNames) {
          // sets the ability of the cells to be edited by the user
          public boolean isCellEditable(int row, int column) {
             return false; // returns false, cannot be edited
          }
       };
       // frames
       JFrame frame, frame1;
       // panels
       JPanel buttonPanel, buttonPanel2, tablePanel, addPanel, editPanel;
       // labels
       JLabel labelGender, labelName, labelCourse, labelYear, labelID;
       // text fields
       JTextField txtGender, txtName, txtCourse, txtYear, txtID;
       // buttons
       JButton btnAdd, btnEdit, btnDelete, btnSort, btnSave, btnAddInput, btnCancel;
       // additionals
       int keyCode, rowIndex, rowNumber, noOfStudents;
       // button handler
       ButtonHandler bh = new ButtonHandler();
    
       public MainGUI() {
          // setting/modifying table components
          table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
          table.getSelectionModel().addListSelectionListener(new RowListener());
          table.getColumnModel().getColumn(1).setPreferredWidth(200);
          table.getColumnModel().getColumn(3).setPreferredWidth(50);
          table.getTableHeader().setResizingAllowed(false);
          table.getTableHeader().setReorderingAllowed(false);
          JScrollPane scrollPane = new JScrollPane(table);
    
          // main buttons
          btnAdd = new JButton("ADD");
          btnAdd.addActionListener(bh);
          btnEdit = new JButton("EDIT");
          btnEdit.addActionListener(bh);
          btnEdit.setEnabled(false); // disables the component
          btnDelete = new JButton("DELETE");
          btnDelete.addActionListener(bh);
          btnDelete.setEnabled(false); // disables the component
          btnSort = new JButton("SORT");
          btnSort.addActionListener(bh);
          btnSave = new JButton("SAVE");
          btnSave.addActionListener(bh);
    
          // with button Listeners
    
          // sub buttons
          btnAddInput = new JButton("Add");
          btnAddInput.addActionListener(bh);
          btnCancel = new JButton("Cancel");
          btnCancel.addActionListener(bh);
    
          // set label names
          labelGender = new JLabel("GENDER");
          labelName = new JLabel("NAME");
          labelCourse = new JLabel("COURSE");
          labelYear = new JLabel("YEAR");
          labelID = new JLabel("ID");
    
          // set text fields width
          txtGender = new JTextField(20);
          txtName = new JTextField(20);
          txtCourse = new JTextField(20);
          txtYear = new JTextField(20);
          txtYear.setDocument(new JTextFieldLimit(1)); // limits the length of
                                                       // input: max of 1
          txtYear.addKeyListener(keyListener); // accepts only numerals
          txtID = new JTextField(20);
          txtID.setDocument(new JTextFieldLimit(7)); // limits the length of input:
                                                     // max of 7
          txtID.addKeyListener(keyListener); // accepts only numerals
    
          // main frame
          // panel for the table
          tablePanel = new JPanel();
          tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
          tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10));
          tablePanel.add(table.getTableHeader());
          tablePanel.add(table);
    
          // panel for the main buttons
          buttonPanel = new JPanel();
          buttonPanel.setLayout(new GridBagLayout());
          GridBagConstraints c = new GridBagConstraints();
    
          // positions the main buttons
          c.gridx = 0;
          c.gridy = 0;
          c.ipady = 20;
          c.insets = new Insets(10, 10, 10, 10);
          c.fill = GridBagConstraints.HORIZONTAL;
          buttonPanel.add(btnAdd, c);
          c.gridx = 0;
          c.gridy = 1;
          c.fill = GridBagConstraints.HORIZONTAL;
          c.ipady = 20;
          c.insets = new Insets(10, 10, 10, 10);
          buttonPanel.add(btnEdit, c);
          c.gridx = 0;
          c.gridy = 2;
          c.fill = GridBagConstraints.HORIZONTAL;
          c.ipady = 20;
          c.insets = new Insets(10, 10, 10, 10);
          buttonPanel.add(btnDelete, c);
          c.gridx = 0;
          c.gridy = 3;
          c.ipady = 20;
          c.insets = new Insets(10, 10, 10, 10);
          c.fill = GridBagConstraints.HORIZONTAL;
          buttonPanel.add(btnSort, c);
          c.gridx = 0;
          c.gridy = 4;
          c.ipady = 20;
          c.insets = new Insets(10, 10, 10, 10);
          c.fill = GridBagConstraints.HORIZONTAL;
          buttonPanel.add(btnSave, c);
    
          frame = new JFrame("Student Database");
          frame.setVisible(true);
          frame.setResizable(false);
          frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
          frame.add(tablePanel, BorderLayout.CENTER);
          frame.add(buttonPanel, BorderLayout.EAST);
          frame.pack();
    
          // ADD frame
          // panel for adding
          addPanel = new JPanel();
          addPanel.setLayout(new GridBagLayout());
    
          // positions the components for adding
          // labels
          c.insets = new Insets(1, 0, 1, 1);
          c.gridx = 0;
          c.gridy = 0;
          addPanel.add(labelID, c);
          c.gridy = 1;
          addPanel.add(labelName, c);
          c.gridy = 2;
          addPanel.add(labelCourse, c);
          c.gridy = 3;
          addPanel.add(labelYear, c);
          c.gridy = 4;
          addPanel.add(labelGender, c);
          // text fields
          c.gridx = 1;
          c.gridy = 0;
          c.ipady = 1;
          addPanel.add(txtID, c);
          c.gridy = 1;
          c.ipady = 1;
          addPanel.add(txtName, c);
          c.gridy = 2;
          c.ipady = 1;
          addPanel.add(txtCourse, c);
          c.gridy = 3;
          c.ipady = 1;
          addPanel.add(txtYear, c);
          c.gridy = 4;
          c.ipady = 1;
          addPanel.add(txtGender, c);
    
          // panel for other necessary buttons
          buttonPanel2 = new JPanel();
          buttonPanel2.setLayout(new GridLayout(1, 1));
          buttonPanel2.add(btnAddInput);
          buttonPanel2.add(btnCancel);
    
          frame1 = new JFrame("Student Database");
          frame1.setVisible(false);
          frame1.setResizable(false);
          frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
          frame1.add(addPanel, BorderLayout.CENTER);
          frame1.add(buttonPanel2, BorderLayout.PAGE_END);
          frame1.pack();
       }// end
    
       KeyListener keyListener = new KeyListener() {
          public void keyTyped(KeyEvent e) {
          }
    
          public void keyPressed(KeyEvent e) {
             keyCode = e.getKeyCode();
    
             if (!(keyCode >= 48 && keyCode <= 57) && !(keyCode >= 96 && keyCode <= 105)
                      && !(keyCode >= 37 && keyCode <= 40) && !(keyCode == 127 || keyCode == 8)) {
                txtID.setEditable(false);
             }
          }
    
          public void keyReleased(KeyEvent e) {
             txtID.setEditable(true);
          }
       };
    
       class RowListener implements ListSelectionListener {
          public void valueChanged(ListSelectionEvent event) {
             if (event.getValueIsAdjusting()) {
                rowIndex = table.getSelectedRow();
                if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
                   btnEdit.setEnabled(false);
                   btnDelete.setEnabled(false);
                } else {
                   btnEdit.setEnabled(true);
                   btnDelete.setEnabled(true);
                }
             }
          }
       }// end
    
       class ButtonHandler implements ActionListener {
          public void actionPerformed(ActionEvent e) {
             try {
                if (e.getActionCommand().equals("ADD")) {
                   // text fields for Student input data
                   txtGender.setText("");
                   txtName.setText("");
                   txtCourse.setText("");
                   txtYear.setText("");
                   txtID.setText("");
    
                   frame1.setTitle("Add Student data"); // title bar name for add
                   btnAddInput.setActionCommand("Add2");
                   btnAddInput.setText("ADD");
    
                   frame1.setVisible(true); // sets the visibility of frame1
                } else if (e.getActionCommand().equals("EDIT")) {
                   txtID.setText(data[rowIndex][4] + ""); // will preview the ID
                                                          // input during Add
                   txtName.setText(data[rowIndex][1] + ""); // will preview the Name
                                                            // input during Add
                   txtCourse.setText(data[rowIndex][2] + ""); // will preview the
                                                              // Course input during
                                                              // Add
                   txtYear.setText(data[rowIndex][3] + ""); // will preview the Year
                                                            // input during Add
                   txtGender.setText(data[rowIndex][0] + ""); // will preview the
                                                              // Gender input during
                                                              // Add
    
                   txtID.setEditable(false); // forbids the user to edit the entered
                                             // ID number
    
                   frame1.setTitle("Edit Student data"); // title bar name for edit
                   btnAddInput.setActionCommand("Edit2");
                   btnAddInput.setText("ACCEPT");
    
                   frame1.setVisible(true); // sets the visibility of frame1
                } else if (e.getActionCommand().equals("DELETE")) {
                   int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
                            JOptionPane.YES_NO_OPTION);
    
                   if (confirm == 0) {
                      rowIndex = table.getSelectedRow();
                      rowNumber = 0;
    
                      noOfStudents--;
                      for (int i = 0; i <= 10; i++) {
                         if (rowIndex != i && i <= noOfStudents) {
                            data[rowNumber][4] = data[i][4];
                            data[rowNumber][1] = data[i][1];
                            data[rowNumber][2] = data[i][2];
                            data[rowNumber][3] = data[i][3];
                            data[rowNumber][0] = data[i][0];
                            rowNumber++;
                         } else if (rowIndex != i && i > noOfStudents) {
                            data[rowNumber][4] = "";
                            data[rowNumber][1] = "";
                            data[rowNumber][2] = "";
                            data[rowNumber][3] = "";
                            data[rowNumber][0] = "";
                            rowNumber++;
                         }
                      }
                      if (noOfStudents == 50) // if the number of students id equal
                                              // to 50, can no longer add students
                         btnAdd.setEnabled(false);
                      else
                         btnAdd.setEnabled(true); // continues to add students if
                                                  // not equal to 50
                      if (noOfStudents == 0) {
                         btnDelete.setEnabled(false);
                         btnEdit.setEnabled(false);
                      } else {
                         btnDelete.setEnabled(true);
                         btnEdit.setEnabled(true);
                      }
    
                      rowIndex = table.getSelectedRow();
                      if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
                         btnEdit.setEnabled(false);
                         btnDelete.setEnabled(false);
                      } else {
                         btnEdit.setEnabled(true);
                         btnDelete.setEnabled(true);
                      }
    
                      table.updateUI();
    
                   }
                } else if (e.getActionCommand().equals("Add2")) {
    
                   if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
                            || txtCourse.getText().isEmpty()// /
                            || txtYear.getText().isEmpty() || txtGender.getText().isEmpty()) {
                      JOptionPane.showMessageDialog(null, "PLEASE FILL IN THE BLANKS.", "ERROR!",
                               JOptionPane.ERROR_MESSAGE);
                   } else {
                      int dup = 0;
                      for (int i = 0; i < 10; i++) {
                         if (txtID.getText().equals(data[i][0])) {
                            JOptionPane.showMessageDialog(null, "ID NUMBER ALREADY EXISTS.", "ERROR!",
                                     JOptionPane.ERROR_MESSAGE);
                            dup++;
                            break;
                         }
                      }
                      if (dup == 0) {
                         rowIndex = table.getSelectedRow();
                         data[noOfStudents][4] = txtID.getText();
                         data[noOfStudents][1] = txtName.getText();
                         data[noOfStudents][2] = txtCourse.getText();
                         data[noOfStudents][3] = txtYear.getText();
                         data[noOfStudents][0] = txtGender.getText();
    
                         table.updateUI();
                         frame1.dispose();
                         noOfStudents++;
                         if (noOfStudents == 50)
                            btnAdd.setEnabled(false);
                         else
                            btnAdd.setEnabled(true);
                         if (data[rowIndex][0] == null) {
                            btnEdit.setEnabled(false);
                            btnDelete.setEnabled(false);
                         } else {
                            btnEdit.setEnabled(true);
                            btnDelete.setEnabled(true);
                         }
                      }
                   }
                   table.updateUI();
                } else if (e.getActionCommand().equals("Edit2")) {
                   if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
                            || txtCourse.getText().isEmpty() || txtYear.getText().isEmpty()
                            || txtGender.getText().isEmpty()) {
                      JOptionPane.showMessageDialog(null, "INCOMPLETE INPUT.", "ERROR!",
                               JOptionPane.ERROR_MESSAGE);
                   } else {
                      data[rowIndex][4] = txtGender.getText();
                      data[rowIndex][1] = txtName.getText();
                      data[rowIndex][2] = txtCourse.getText();
                      data[rowIndex][3] = txtYear.getText();
                      data[rowIndex][0] = txtID.getText();
                      frame1.dispose();
                   }
    
                   table.updateUI();
    
                } else if (e.getActionCommand().equals("Cancel")) {
                   frame1.dispose();
                }
    
             } catch (Exception error) {
             }
    
          }
       }// end
    
       class JTextFieldLimit extends PlainDocument {
          private int limit;
    
          JTextFieldLimit(int limit) {
             super();
             this.limit = limit;
          }
    
          JTextFieldLimit(int limit, boolean upper) {
             super();
             this.limit = limit;
          }
    
          public void insertString(int offset, String str, AttributeSet attr)
                   throws BadLocationException {
             if (str == null)
                return;
    
             if ((getLength() + str.length()) <= limit) {
                super.insertString(offset, str, attr);
             }
          }
       }// end
    
       public static void main(String[] args) {
          new MainGUI();
       }// end of main
    
    }// end of class
    Much luck and welcome to the forum!

  4. #4
    florachu2121 is offline Member
    Join Date
    Jul 2010
    Location
    ASIA
    Posts
    3
    Rep Power
    0

    Default

    Hi :) i did this code for the SAVE button and it is working fine.
    but i dont get the "...and that since it should be an "object" file, the data should be serialized"
    i opened the output.dat file and it is pretty much like the log.txt...so am I wrong?
    coz my teacher included another file "input.dat" and when i open it, it is way different than my object.dat

    else if( e.getActionCommand().equals( "SAVE" ) ){
    try{
    FileWriter fw= new FileWriter("output.dat",true);
    FileWriter fw2= new FileWriter("log.txt",true);
    for (int r=0; r<data.length; r++){
    String data1="";
    for (int c=0; c<data[r].length; c++){
    if(data[r][c] != null){
    data1 = data1+ (String)data[r][c]+"-";
    }
    }
    if(data1.trim().length() > 0){
    fw.write(data1+System.getProperty("line.separator" ));
    fw2.write(data1+System.getProperty("line.separator "));
    }
    }
    fw.flush();
    fw2.flush();
    fw.close();
    fw2.close();

    }catch(IOException ioe){
    System.out.println(ioe.getMessage());
    }

    }

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    The instructions leave some room for interpretation.
    saves the current content of the course (together with the list of
    students) under the filename output.dat (object file).
    *** Store all successful transactions within a text file named log.txt ***
    Do you have a definition of what an "object file" is? One definition could be what is written to an ObjectOutputStream using the writeObject method.
    That is what the data should be serialized would mean.
    Writing an object to a disk file is known as serialization.

  6. #6
    florachu2121 is offline Member
    Join Date
    Jul 2010
    Location
    ASIA
    Posts
    3
    Rep Power
    0

    Default

    THANKS! now it is finished.
    damn, now i know what u mean after so many hours.


    our defense is today.
    thanx for the help, God Bless :)

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. How can i save the data Internally(auto save)
    By Rama Koti Reddy in forum AWT / Swing
    Replies: 2
    Last Post: 11-01-2010, 09:31 PM
  2. Replies: 7
    Last Post: 08-17-2010, 07:00 PM
  3. Create a form, input some data and save to file
    By cselic in forum AWT / Swing
    Replies: 5
    Last Post: 05-07-2010, 01:28 PM
  4. Reading data from a text file
    By Cheguvara in forum New To Java
    Replies: 2
    Last Post: 02-02-2010, 03:33 PM
  5. Edit/Save Text File - Problems
    By ryanlbowen in forum New To Java
    Replies: 9
    Last Post: 07-20-2009, 06:23 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •