I have a code that read file and store in arraylist and then convert to array(To use for table model)
My class extends abstracttablemodel correctly.
My All Code is:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
public class ReadFileToList extends AbstractTableModel{
String[] col={"Fname","Lname","Number"};
List<String> data=new ArrayList<String>();
String[][] Arraydata;
public ReadFileToList(){
try{
FileReader fr=new FileReader("D:\\AllUserRecords.txt");
BufferedReader br=new BufferedReader(fr);
String line;
while((line=br.readLine()) !=null){
data.add(line);
}
br.close();
Arraydata=(String[][]) data.toArray();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
@Override
public String getColumnName(int colu){
return col[colu];
}
public int getRowCount() {
return Arraydata.length;
}
public int getColumnCount() {
return col.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return Arraydata[rowIndex][columnIndex];
}
}
My main Class is ReadFileToListM:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class ReadFileToListM {
ReadFileToList rftl=new ReadFileToList();
public ReadFileToListM(){
JFrame frame=new JFrame();
JTable table=new JTable(rftl);
JPanel panel=new JPanel();
JScrollPane sp=new JScrollPane(table);
panel.add(sp);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(470,470);
frame.setVisible(true);
}
public static void main(String[] args){
new ReadFileToListM();
}
}
but it has Exception!
this is my Exceptions:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.String;
at javaapplication1.ReadFileToList.<init>(ReadFileToList.java:37)
at javaapplication1.ReadFileToListM.<init>(ReadFileToListM.java:8)
at javaapplication1.ReadFileToListM.main(ReadFileToListM.java:22)
Java Result: 1
My txt File:
FName Lname Number
second secondsecond 22
thired thithird 33
fourth fourfourr 44
fifth fiffif 55
Please help me, Thanks.
Contructor of the ReadFileToList class is empty, you should change:
to
because if dont do that initialization of your model(code below) doesnt execute your method which put data in your collections but only execute contructor from extended class.
2nd
You can’t cast List which is one-dimential dynamic sized array to two-dimential array. Other methods from your model looks good.
Also you should somehow seperate data from the File. At this moment it’s only splitted to to rows.
It will be really helpful if you show us few lines from the file.
EDIT: 06-01-2013 After posting file content Change Countructor in model to this one
main should look like this
Result:
