Pergunta

I am working on a student attendance database but I have no idea how to load the text file created from the jtable back into the same jtable? I have already checked the api docs and surf the net for potential hints but was unable to get the table read properly.

This is my code so far:

public class AttendanceArchive extends JFrame {

private JPanel contentPane;
private JTextField txtStudentName;
private JTable table;
private ScrollPane scrollPane;




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

/**
 * Create the frame.
 */
public AttendanceArchive() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 726, 516);
    setLocationRelativeTo(null);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);



    File dir = new File("C:/GCK Database/Attendance/");
    File[] Filename = dir.listFiles();
    if (Filename.length == 0) {
        txtStudentName = new JTextField();
        txtStudentName.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                txtStudentName.setText("");
            }
        });
        txtStudentName.setBackground(Color.WHITE);
        txtStudentName.setText("STUDENT NAME");
        txtStudentName.setBounds(25, 22, 262, 20);
        contentPane.add(txtStudentName);
        txtStudentName.setColumns(10);

        JLabel lblViewBy = new JLabel("VIEW BY");
        lblViewBy.setFont(new Font("Tahoma", Font.BOLD, 12));
        lblViewBy.setBounds(25, 53, 57, 14);
        contentPane.add(lblViewBy);

        table = new JTable(){
               @Override
               public boolean isCellEditable(int row, int column) {
                return false;
               }
              };
        table.setCellSelectionEnabled(true);
                table.getTableHeader().setReorderingAllowed(false);
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                getContentPane().add(table);
                final DefaultTableModel tableModel = new DefaultTableModel(new Object[]{"Student Name","Student ID"},0);
                int q = table.getSelectedColumn();
                int r = table.getSelectedRow();
                table.setModel(tableModel);
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String click1 = (String) table.getValueAt(table.getSelectedRow(),table.getColumnCount()-1) ;
                int click2 = Integer.parseInt(click1);
                int q = table.getSelectedColumn();
                int r = table.getSelectedRow();
                Object p = table.getValueAt(r,q);
                String t = null;
                String  b = p.toString();

                switch (b) {
                case "1":  t = "L";

                       break;
                case "L":  t = "0";
                           click2++;
                       break;
                case "0":  t = "1"; 
                           click2--;
                       break;
                default: t = b;
                break;
                }

                String click3 = Integer.toString(click2);

                tableModel.setValueAt(click3,r,table.getColumnCount()-1);
                tableModel.setValueAt(t,r,q);
            }
        });




        String[] years = { "2008", "2009", "2010", "2011", "2012", "2013", "2014" };
        final JComboBox comboBox_2 = new JComboBox(years);
        comboBox_2.setEditable(true);
        comboBox_2.setBounds(532, 22, 115, 20);
        contentPane.add(comboBox_2);

        String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
        final JComboBox comboBox_1 = new JComboBox(months);
        comboBox_1.setBounds(410, 22, 115, 20);
        contentPane.add(comboBox_1);


        table.setBounds(25, 143, 381, 296);
        contentPane.add(table);


        JButton btnGo = new JButton("Go");
        btnGo.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int x = 0;
                if (comboBox_1.getSelectedItem() == "January"){
                    tableModel.setColumnCount(2);
                    x = 0;
                }
                if (comboBox_1.getSelectedItem() == "February"){
                    tableModel.setColumnCount(2);
                    x = 1;
                }
                if (comboBox_1.getSelectedItem() == "March"){
                    tableModel.setColumnCount(2);
                    x = 2;
                }
                if (comboBox_1.getSelectedItem() == "April"){
                    tableModel.setColumnCount(2);
                    x = 3;
                }
                if (comboBox_1.getSelectedItem() == "May"){
                    tableModel.setColumnCount(2);
                    x = 4;
                }
                if (comboBox_1.getSelectedItem() == "June"){
                    tableModel.setColumnCount(2);
                    x = 5;
                }
                if (comboBox_1.getSelectedItem() == "July"){
                    tableModel.setColumnCount(2);
                    x = 6;
                }
                if (comboBox_1.getSelectedItem() == "August"){
                    tableModel.setColumnCount(2);
                    x = 7;
                }
                if (comboBox_1.getSelectedItem() == "September"){
                    tableModel.setColumnCount(2);
                    x = 8;
                }
                if (comboBox_1.getSelectedItem() == "October"){
                    tableModel.setColumnCount(2);
                    x = 9;
                }
                if (comboBox_1.getSelectedItem() == "November"){
                    tableModel.setColumnCount(2);
                    x = 10;
                }
                if (comboBox_1.getSelectedItem() == "December"){
                    tableModel.setColumnCount(2);
                    x = 11;
                }

                Calendar calendar = Calendar.getInstance();
                int year = Integer.parseInt((String) comboBox_2.getSelectedItem());
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, x);
                int numDays = calendar.getActualMaximum(Calendar.DATE);
                for(int p=1;p<=numDays;p++){
                    tableModel.addColumn(p);


                }
                tableModel.addColumn("Absentees");




                File dir = new File("C:/GCK Database/Attendance/");
                dir.mkdir();
                File dir2 = new File("C:/GCK Database/Student Profile/");
                if (dir2.exists()){
                File[] Filename = dir2.listFiles();
                for( int p = tableModel.getRowCount() - 1; p >= 0; p-- ) {
                    tableModel.removeRow(p);
              }
                for (int i = 0; i < Filename.length; i++) {
                      ArrayList<Double> data = new ArrayList<Double>();
                    try {
                        BufferedReader br = new BufferedReader(new FileReader("C:/GCK Database/Student Profile/"+Filename[i].getName()+ "/" + Filename[i].getName()+ ".txt"));
                        List<String> lines = new ArrayList<String>();
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            lines.add(line);
                        }
                        br.close();
                        lines.toArray(new String[lines.size()]);
                        if (numDays == 28) {
                            tableModel.addRow(new Object[]{Filename[i].getName(),lines.get(1),"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","0"});

                        } else if (numDays == 29){

                            tableModel.addRow(new Object[]{Filename[i].getName(),lines.get(1),"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","0"});

                        } else if (numDays == 30){

                            tableModel.addRow(new Object[]{Filename[i].getName(),lines.get(1),"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","0"});

                        }else if (numDays == 31){

                            tableModel.addRow(new Object[]{Filename[i].getName(),lines.get(1),"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","0"});

                        } else {

                            tableModel.addRow(new Object[]{Filename[i].getName(),lines.get(1),"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","0"});

                        }

                    } catch (IOException e1) {

                    }

                }

                }
                else {

                }
            }
        });
        btnGo.setHorizontalAlignment(SwingConstants.LEADING);
        btnGo.setBounds(656, 21, 52, 23);
        contentPane.add(btnGo);

        String [] sort = {"Name", "ID"};
        final JComboBox comboBox = new JComboBox(sort);
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String arrange = (String)comboBox.getSelectedItem();
                if (arrange == "Name") {
                       TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel());

                       sorter.setComparator(0, new Comparator<Object>() {
                            @Override
                            public int compare(Object arg0, Object arg1) {
                                return arg0.toString().toLowerCase().compareTo(arg1.toString().toLowerCase());
                            }
                        });
                       sorter.toggleSortOrder(0);
                       table.setRowSorter(sorter);
                       table.setModel(tableModel);
                }
                if (arrange == "ID") {
                       TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel());

                       sorter.setComparator(0, new Comparator<Object>() {
                            @Override
                            public int compare(Object arg0, Object arg1) {
                                return arg0.toString().compareTo(arg1.toString());
                            }
                        });
                       sorter.toggleSortOrder(1);
                       table.setRowSorter(sorter);
                       table.setModel(tableModel);
                }                  

            }
        });
        comboBox.setBounds(92, 53, 141, 20);
        contentPane.add(comboBox);

        JButton btnCancel = new JButton("Back");
        btnCancel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                homepage home = new homepage();
                home.setVisible(true);
                dispose();
            }
        });
        btnCancel.setBounds(10, 450, 89, 23);
        contentPane.add(btnCancel);

        JButton btnSearch = new JButton("Search");
        btnSearch.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                int x = 0;
                if (comboBox_1.getSelectedItem() == "January"){
                    tableModel.setColumnCount(2);
                    x = 0;
                }
                if (comboBox_1.getSelectedItem() == "February"){
                    tableModel.setColumnCount(2);
                    x = 1;
                }
                if (comboBox_1.getSelectedItem() == "March"){
                    tableModel.setColumnCount(2);
                    x = 2;
                }
                if (comboBox_1.getSelectedItem() == "April"){
                    tableModel.setColumnCount(2);
                    x = 3;
                }
                if (comboBox_1.getSelectedItem() == "May"){
                    tableModel.setColumnCount(2);
                    x = 4;
                }
                if (comboBox_1.getSelectedItem() == "June"){
                    tableModel.setColumnCount(2);
                    x = 5;
                }
                if (comboBox_1.getSelectedItem() == "July"){
                    tableModel.setColumnCount(2);
                    x = 6;
                }
                if (comboBox_1.getSelectedItem() == "August"){
                    tableModel.setColumnCount(2);
                    x = 7;
                }
                if (comboBox_1.getSelectedItem() == "September"){
                    tableModel.setColumnCount(2);
                    x = 8;
                }
                if (comboBox_1.getSelectedItem() == "October"){
                    tableModel.setColumnCount(2);
                    x = 9;
                }
                if (comboBox_1.getSelectedItem() == "November"){
                    tableModel.setColumnCount(2);
                    x = 10;
                }
                if (comboBox_1.getSelectedItem() == "December"){
                    tableModel.setColumnCount(2);
                    x = 11;
                }

                Calendar calendar = Calendar.getInstance();
                int year = Integer.parseInt((String) comboBox_2.getSelectedItem());
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, x);
                int numDays = calendar.getActualMaximum(Calendar.DATE);
                for(int p=1;p<=numDays;p++){
                    tableModel.addColumn(p);


                }
                tableModel.addColumn("Absentees");

                  File dir = new File("C:\\GCK Database\\Student Profile");
                  FilenameFilter filter = new FilenameFilter() {
                     public boolean accept
                     (File dir, String name) {
                        return name.toLowerCase().contains(txtStudentName.getText().toLowerCase());
                    }
                  };
                  String[] children = dir.list(filter);
                  if (children == null) {


                  } 
                  else {
                      for( int p = tableModel.getRowCount() - 1; p >= 0; p-- ) {
                            tableModel.removeRow(p);
                      }
                     for (int s=0; s < children.length; s++) {
                        String filename = children[s];
                        try {
                            BufferedReader br = new BufferedReader(new FileReader("C:/GCK Database/Student Profile/"+filename+ "/" + filename+ ".txt"));
                            List<String> lines = new ArrayList<String>();
                            String line = null;
                            while ((line = br.readLine()) != null) {
                                lines.add(line);
                            }
                            br.close();
                            lines.toArray(new String[lines.size()]);
                            if (numDays == 28) {
                                tableModel.addRow(new Object[]{filename,lines.get(1),"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","0"});

                            } else if (numDays == 29){

                                tableModel.addRow(new Object[]{filename,lines.get(1),"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","0"});

                            } else if (numDays == 30){

                                tableModel.addRow(new Object[]{filename,lines.get(1),"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","0"});

                            }else if (numDays == 31){

                                tableModel.addRow(new Object[]{filename,lines.get(1),"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","0"});

                            } else {

                                tableModel.addRow(new Object[]{filename,lines.get(1),"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","0"});

                            }
                        } catch (IOException e) {

                        }

                     }
                  }
            }
        });
        btnSearch.setBounds(307, 21, 89, 23);
        contentPane.add(btnSearch);

        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBounds(10, 84, 698, 355);
        contentPane.add(scrollPane);
        ColumnsAutoSizer.sizeColumnsToFit(table);

        JButton btnPrint = new JButton("Print");
        btnPrint.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    if (! table.print()) {

                    }
                } catch (java.awt.print.PrinterException e1) {
                    JOptionPane.showMessageDialog( null , "Could not find printer");
                }

            }
        });
        btnPrint.setBounds(504, 450, 89, 23);
        contentPane.add(btnPrint);

        JButton btnSave = new JButton("Save");
        btnSave.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {

                StringBuffer sbTableData = new StringBuffer();
                for(int row = 0; row < table.getRowCount(); row ++){
                    for(int column = 0; column < table.getColumnCount(); column ++){
                        sbTableData.append(table.getValueAt(row, column)).append(System.getProperty("line.separator"));
                    }
                    sbTableData.append(System.getProperty("line.separator"));
                }
                FileWriter fileWriter;
                try {
                    String line;
                    int e = 0;
                    File dir = new File("C:/GCK Database");
                    dir.mkdir();
                    File dir1 = new File("C:/GCK Database/Attendance");
                    dir1.mkdir();
                    File dir2 = new File("C:/GCK Database/Attendance/" + comboBox_2.getSelectedItem());
                    dir2.mkdir();
                    File dir3 = new File("C:/GCK Database/Attendance/" + comboBox_2.getSelectedItem() + "/" + comboBox_1.getSelectedItem());
                    dir3.mkdir();
                      BufferedWriter bfw = new BufferedWriter(new FileWriter("C:/GCK Database/Attendance/" + comboBox_2.getSelectedItem() + "/" + comboBox_1.getSelectedItem() + "/Attendance " + comboBox_1.getSelectedItem() + " " + comboBox_2.getSelectedItem() + ".txt"));
                      for(int i = 0 ; i < table.getColumnCount() ; i++)
                      {
                        bfw.write(table.getColumnName(i));
                        bfw.write("\t");
                      }

                      for (int i = 0 ; i < table.getRowCount(); i++)
                      {
                        bfw.newLine();
                        for(int j = 0 ; j < table.getColumnCount();j++)
                        {
                          bfw.write((String)(table.getValueAt(i,j)));
                          bfw.write("\t");;
                        }
                      }
                      bfw.close();


                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }
        });
        btnSave.setBounds(619, 450, 89, 23);
        contentPane.add(btnSave);

        JButton btnViewStudentProfile = new JButton("View Student Profile");
        btnViewStudentProfile.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                if (table.getSelectedRow() != -1) {
                    int selectedRow = table.getSelectedRow();
                    String selectedRow1 = (String) table.getModel().getValueAt(selectedRow, 0);
                    SPInfo view = new SPInfo(selectedRow1);
                    view.addname(selectedRow1);
                    view.setVisible(true);
                    dispose();
                    }
                    else {

                    }

            }
        });
        btnViewStudentProfile.setBounds(269, 450, 156, 23);
        contentPane.add(btnViewStudentProfile);

        JLabel lblKeys = new JLabel("Keys:");
        lblKeys.setFont(new Font("Tahoma", Font.BOLD, 11));
        lblKeys.setBounds(410, 54, 46, 14);
        contentPane.add(lblKeys);

        JLabel lblPresent = new JLabel("1 - Present        L - Late      0 - Absent");
        lblPresent.setBackground(Color.WHITE);
        lblPresent.setBounds(449, 54, 259, 14);
        contentPane.add(lblPresent);


    } else {

                   I want to place the coding for same jtable as above but with the content from the text file  here


    }



}
public ScrollPane getScrollPane() {
    return scrollPane;
}
}

Here is the updated version:

speed foward to before else which is the same as above

    } else {


        txtStudentName = new JTextField();
        txtStudentName.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                txtStudentName.setText("");
            }
        });
        txtStudentName.setBackground(Color.WHITE);
        txtStudentName.setText("STUDENT NAME");
        txtStudentName.setBounds(25, 22, 262, 20);
        contentPane.add(txtStudentName);
        txtStudentName.setColumns(10);

        JLabel lblViewBy = new JLabel("VIEW BY");
        lblViewBy.setFont(new Font("Tahoma", Font.BOLD, 12));
        lblViewBy.setBounds(25, 53, 57, 14);
        contentPane.add(lblViewBy);

        table = new JTable(){
               @Override
               public boolean isCellEditable(int row, int column) {
                return false;
               }
              };

        table.setCellSelectionEnabled(true);
                table.getTableHeader().setReorderingAllowed(false);
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                getContentPane().add(table);
                final DefaultTableModel tableModel = new DefaultTableModel(new Object[]{"Student Name","Student ID"},0);
                int q = table.getSelectedColumn();
                int r = table.getSelectedRow();
                table.setModel(tableModel);
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String click1 = (String) table.getValueAt(table.getSelectedRow(),table.getColumnCount()-1) ;
                int click2 = Integer.parseInt(click1);
                int q = table.getSelectedColumn();
                int r = table.getSelectedRow();
                Object p = table.getValueAt(r,q);
                String t = null;
                String  b = p.toString();

                switch (b) {
                case "1":  t = "L";

                       break;
                case "L":  t = "0";
                           click2++;
                       break;
                case "0":  t = "1"; 
                           click2--;
                       break;
                default: t = b;
                break;
                }

                String click3 = Integer.toString(click2);

                tableModel.setValueAt(click3,r,table.getColumnCount()-1);
                tableModel.setValueAt(t,r,q);
            }
        });





        String[] years = { "2008", "2009", "2010", "2011", "2012", "2013", "2014" };
        final JComboBox comboBox_2 = new JComboBox(years);
        comboBox_2.setEditable(true);
        comboBox_2.setBounds(532, 22, 115, 20);
        contentPane.add(comboBox_2);

        String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
        final JComboBox comboBox_1 = new JComboBox(months);
        comboBox_1.setBounds(410, 22, 115, 20);
        contentPane.add(comboBox_1);


        table.setBounds(25, 143, 381, 296);
        contentPane.add(table);


        JButton btnGo = new JButton("Go");
        btnGo.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

I want to place the coding for reading and insert to jtable here

            }
        });
        btnGo.setHorizontalAlignment(SwingConstants.LEADING);
        btnGo.setBounds(656, 21, 52, 23);
        contentPane.add(btnGo);

        String [] sort = {"Name", "ID"};
        final JComboBox comboBox = new JComboBox(sort);
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String arrange = (String)comboBox.getSelectedItem();
                if (arrange == "Name") {
                       TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel());

                       sorter.setComparator(0, new Comparator<Object>() {
                            @Override
                            public int compare(Object arg0, Object arg1) {
                                return arg0.toString().toLowerCase().compareTo(arg1.toString().toLowerCase());
                            }
                        });
                       sorter.toggleSortOrder(0);
                       table.setRowSorter(sorter);
                       table.setModel(tableModel);
                }
                if (arrange == "ID") {
                       TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel());

                       sorter.setComparator(0, new Comparator<Object>() {
                            @Override
                            public int compare(Object arg0, Object arg1) {
                                return arg0.toString().compareTo(arg1.toString());
                            }
                        });
                       sorter.toggleSortOrder(1);
                       table.setRowSorter(sorter);
                       table.setModel(tableModel);
                }                  

            }
        });
        comboBox.setBounds(92, 53, 141, 20);
        contentPane.add(comboBox);

        JButton btnCancel = new JButton("Back");
        btnCancel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                homepage home = new homepage();
                home.setVisible(true);
                dispose();
            }
        });
        btnCancel.setBounds(10, 450, 89, 23);
        contentPane.add(btnCancel);

        JButton btnSearch = new JButton("Search");
        btnSearch.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {



            }
        });
        btnSearch.setBounds(307, 21, 89, 23);
        contentPane.add(btnSearch);

        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBounds(10, 84, 698, 355);
        contentPane.add(scrollPane);
        ColumnsAutoSizer.sizeColumnsToFit(table);

        JButton btnPrint = new JButton("Print");
        btnPrint.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    if (! table.print()) {

                    }
                } catch (java.awt.print.PrinterException e1) {
                    JOptionPane.showMessageDialog( null , "Could not find printer");
                }

            }
        });
        btnPrint.setBounds(504, 450, 89, 23);
        contentPane.add(btnPrint);

        JButton btnSave = new JButton("Save");
        btnSave.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {

                StringBuffer sbTableData = new StringBuffer();
                for(int row = 0; row < table.getRowCount(); row ++){
                    for(int column = 0; column < table.getColumnCount(); column ++){
                        sbTableData.append(table.getValueAt(row, column)).append(System.getProperty("line.separator"));
                    }
                    sbTableData.append(System.getProperty("line.separator"));
                }
                FileWriter fileWriter;
                try {
                    String line;
                    int e = 0;
                    File dir = new File("C:/GCK Database");
                    dir.mkdir();
                    File dir1 = new File("C:/GCK Database/Attendance");
                    dir1.mkdir();
                    File dir2 = new File("C:/GCK Database/Attendance/" + comboBox_2.getSelectedItem());
                    dir2.mkdir();
                    File dir3 = new File("C:/GCK Database/Attendance/" + comboBox_2.getSelectedItem() + "/" + comboBox_1.getSelectedItem());
                    dir3.mkdir();
                      BufferedWriter bfw = new BufferedWriter(new FileWriter("C:/GCK Database/Attendance/" + comboBox_2.getSelectedItem() + "/" + comboBox_1.getSelectedItem() + "/Attendance " + comboBox_1.getSelectedItem() + " " + comboBox_2.getSelectedItem() + ".txt"));
                      for(int i = 0 ; i < table.getColumnCount() ; i++)
                      {
                        bfw.write(table.getColumnName(i));
                        bfw.write("\t");
                      }

                      for (int i = 0 ; i < table.getRowCount(); i++)
                      {
                        bfw.newLine();
                        for(int j = 0 ; j < table.getColumnCount();j++)
                        {
                          bfw.write((String)(table.getValueAt(i,j)));
                          bfw.write("\t");;
                        }
                      }
                      bfw.close();


                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }
        });
        btnSave.setBounds(619, 450, 89, 23);
        contentPane.add(btnSave);

        JButton btnViewStudentProfile = new JButton("View Student Profile");
        btnViewStudentProfile.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                if (table.getSelectedRow() != -1) {
                    int selectedRow = table.getSelectedRow();
                    String selectedRow1 = (String) table.getModel().getValueAt(selectedRow, 0);
                    SPInfo view = new SPInfo(selectedRow1);
                    view.addname(selectedRow1);
                    view.setVisible(true);
                    dispose();
                    }
                    else {

                    }

            }
        });
        btnViewStudentProfile.setBounds(269, 450, 156, 23);
        contentPane.add(btnViewStudentProfile);

        JLabel lblKeys = new JLabel("Keys:");
        lblKeys.setFont(new Font("Tahoma", Font.BOLD, 11));
        lblKeys.setBounds(410, 54, 46, 14);
        contentPane.add(lblKeys);

        JLabel lblPresent = new JLabel("1 - Present        L - Late      0 - Absent");
        lblPresent.setBackground(Color.WHITE);
        lblPresent.setBounds(449, 54, 259, 14);
        contentPane.add(lblPresent);




    }






}
public ScrollPane getScrollPane() {
    return scrollPane;
}

}

Foi útil?

Solução

Assuming your file data is in row/tabular format, just read it line by line, and split each line into an array, then add it to the DefaultTableModel then set the model for the table, something like

public void getDataFromFile(File file, JTable table) {
    String[] colNames  = { "Your", "Column", "Names", "Go", "Here" };
    DefaultTableModel model = new DefaultTableModel(colNames, 0);

    try (BufferedReader br = new BufferedReader(new FileReader(file)) {
        String line;
        while ((line = br.readLine()) != null) {
            String[] data = line.split("\\s+");
            model.addRow(data);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    table.setModel(model);
}

UPDATE

"My column name and size is not set but it can be obtained from the first line of the text file so how am i going to set those column name and size depending on the text file? "

Don't worry about setting the size. Just construct a default model, then use setColumnIdentifiers() after getting the first line. Then add the rows.

DefaultTableModel model = new DefaultTableModel();

try (BufferedReader br = new BufferedReader(new FileReader(file)) {

    String line = br.readLine();
    String[] colHeaders = line.split("\\s+");
    model.setColumnIdentifiers(colHeaders);

    while ((line = br.readLine()) != null) {
        String[] data = line.split("\\s+");
        model.addRow(data);
    }
}

This is all assuming your data is space delimited


Javadocs

  • public DefaultTableModel() - Constructs a default DefaultTableModel which is a table of zero columns and zero rows.

  • public void setColumnIdentifiers(Object[] newIdentifiers) - Replaces the column identifiers in the model. If the number of newIdentifiers is greater than the current number of columns, new columns are added to the end of each row in the model. If the number of newIdentifiers is less than the current number of columns, all the extra columns at the end of a row are discarded.


UPDATE 2

} else {
    DefaultTableModel model = new DefaultTableModel();

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));

        String line = br.readLine();
        String[] colHeaders = line.split("\\s+");

        model.setColumnIdentifiers(colHeaders);

        while ((line = br.readLine()) != null) {
            String[] data = line.split("\\s+");
            model.addRow(data);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    table.setModel(model);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top