2014-05-07 67 views
0

我正在學習考勤數據庫上工作,但我不知道如何將從jtable創建的文本文件加載回同一個jtable中?我已經檢查過api文檔並上網查看潛在提示,但無法正確讀取表格。如何將jtable保存到文本文件並將其讀回jtable

這是到目前爲止我的代碼:

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

}

+0

究竟哪裏有問題? –

+0

也搜索'我如何比較Java中的字符串?' - 我懶得連接它 –

+0

這段代碼沒有問題,因爲我已經解決了這個問題,但是我想讓jtable從前面的操作中讀取已保存的文本文件,這就是問題所在,因爲我不知道如何使其讀取文本文件並將其設置爲jtable。我想在這個else語句後面的程序的底部放置這個代碼。 – user2972181

回答

2

假設你的文件數據行/列表格式,只是讀它一行行,每行分成數組,然後將其添加到DefaultTableModel然後設置表的模型,像

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

「我的列名和大小沒有設置,但它可以得到從文本文件的第一行開始,那麼我將如何根據文本文件設置這些列名稱和大小? 「

不要擔心設置的容量,只需建立一個默認模型,然後使用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) - 替換模型中的列標識符。如果newIdentifiers的數量大於當前的列數,則將新列添加到模型中每行的末尾。如果newIdentifiers的數量小於當前的列數,則會放棄行末尾的所有額外列。


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

我的專欄由\ t隔開,所以它仍然適用? – user2972181

+0

它應該不會影響'\\ s +'處理所有空間。如果你的數據有一些字段有空格,說出一個拳頭和姓,那麼你可能需要使用tab。試試兩者都出 –

+0

你是什麼意思標籤?對不起,因爲我不知道什麼是一個標籤 – user2972181