อ่านไฟล์ .txt ลงใน JTable ผู้รุ้ ช่วยดู Code ให้หน่อยคับ ทำแล้วมันไม่เอามาแสดงใน Table อะครับ
package Program;
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel;
/** * * @author Lee */ public class Phonebook extends javax.swing.JFrame { public static final String FILE_NAME = "C:\\Users\\Lee\\Desktop\\Phonebook\\FILE_NAME.TXT"; private DefaultTableModel model; String line = null ; public Phonebook() { initComponents(); readFileToModel(); }
@SuppressWarnings("unchecked")
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane(); table = new javax.swing.JTable(); txtKeyword = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); cmdSearch = new javax.swing.JButton(); cmdEdit = new javax.swing.JButton(); cmdAdd = new javax.swing.JButton(); cmdDelete = new javax.swing.JButton();
private void cmdDeleteActionPerformed(java.awt.event.ActionEvent evt) { }
private void cmdSearchActionPerformed(java.awt.event.ActionEvent evt) { for (int row = 0; row < table.getRowCount(); row++){ String s = (String) model.getValueAt(row, 0); if (s.equals(txtKeyword.getText())){ table.setRowSelectionInterval(row, row); table.scrollRectToVisible(table.getCellRect(row, 0, true)); return; } } JOptionPane.showMessageDialog(this, "หาไม่พบ"); }
/** * @param args the command line arguments */ public static void main(String args[]) { @Override public void run() { new Phonebook().setVisible(true); } }); } private void readFileToModel() { String[] columnNames ={"ชื่อ","นามสกุล","อีเมล"}; model = new DefaultTableModel (columnNames, 0); table.setModel(model); File file = new File (FILE_NAME); if (!file.exists()){ return; } try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); while (line != null) { String[] row = line.split(","); model.addRow(row); line = br.readLine(); } br.close(); }catch (Exception ex){ JOptionPane.showMessageDialog(this, ex); } }
// Variables declaration - do not modify private javax.swing.JButton cmdAdd; private javax.swing.JButton cmdDelete; private javax.swing.JButton cmdEdit; private javax.swing.JButton cmdSearch; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable table; private javax.swing.JTextField txtKeyword; // End of variables declaration } งงมากเลยคับ
|