如何将jtable保存到文本文件并将其读回jtable

时间:2014-05-07 10:55:38

标签: java jtable

我正在研究学生出勤数据库,但我不知道如何将从jtable创建的文本文件加载到同一个jtable中?我已经检查过api文档并上网查看潜在的提示但是无法正确读取表格。

到目前为止,这是我的代码:

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

以下是更新版本:

快速前往其他地方,与上述相同

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

我想把编码放在阅读中并插入jtable这里

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

}

1 个答案:

答案 0 :(得分:3)

假设您的文件数据是行/表格格式,只需逐行读取,并将每行拆分成一个数组,然后将其添加到DefaultTableModel然后设置表的模型,如< / p>

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

<强>更新

  

“我的列名和大小未设置,但可以从文本文件的第一行获取,那么我将如何根据文本文件设置这些列名称和大小?”

不要担心设置尺寸。只需构造一个默认模型,然后在获取第一行后使用setColumnIdentifiers()。然后添加行。

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

这是假设您的数据是以空格分隔的


Javadoc中

  • public DefaultTableModel() - 构造一个默认的DefaultTableModel,它是一个零列和零行的表。

  • public void setColumnIdentifiers(Object[] newIdentifiers) - 替换模型中的列标识符。如果newIdentifier的数量大于当前列数,则会将新列添加到模型中每行的末尾。如果newIdentifier的数量小于当前列数,则丢弃行末尾的所有额外列。


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