Coder ACJHP Coder ACJHP - 2 months ago 20
Java Question

JTable does not show Object [][] data

I need to some help about JTable.I'm trying to read data from "Contact.txt" file and populate my table with that datas.I can get data from file correctly with adding to Object[][] 2D array without any problem.When I try to add this Object array to table not happens any thing.
Sorry for my bad English.

Contacts.txt file include "Name","LastName","Phone Num","Email" s.

And this Class read the text and add it to Object :

public class ReadFromText {

public boolean ReadTable(Object [][] data) {

boolean status = false;

File file = new File("/Users/MacbookPro/Documents/Contacts.txt");
BufferedReader bf = null;
FileReader fileReader = null;
try {
fileReader = new FileReader(file);
bf = new BufferedReader(fileReader);

String textLine = null;
String [] text = null;

for (int i = 0; i < data.length; i++) {
for (int j = 0; j < 4; j++) {
while ((textLine = bf.readLine()) != null) {
text = textLine.split(" ");
data[i][j] = text[j];
status = true;

} catch (IOException e) {
return status;

This part of code from main Class :

Object [][]datas = new Object[10][4];

ReadFromText r = new ReadFromText(); //new object from ReadData class
if(r.ReadTable(datas)== true){
System.out.println("OK");//just for to be sure
model = new DefaultTableModel(datas, columNames);
table = new JTable(model);
table.setFont(new Font("Monospaced", Font.PLAIN, 13));
table.setBackground(new Color(245, 245, 245));
table.setMinimumSize(new Dimension(60, 20));

It' return "OK" check it from here

But JTable is empty !!! : look it from this picture

I hope to anyone can help me.THANKS FOR ALL


Your code to read the data from the file is wrong. Think about it for a minute. You start the outer loop with a value of 0, then you have you inner loop with a value of 0 and then you read the entire file using the while loop.

You want your logic to read a single line of data, split that line and add then add the data to the array. So the logic should be something like:

int row = 0;

while ((String textLine = bf.readLine()) != null) 
    String text = textLine.split("    ");

    for (int i = 0; i < text.length; i++)
         data[row][i] = text[i];


However, you should NOT be using Arrays to hold the data. You should never hardcode the size of a data structure since it does not allow you to add new data. Instead you should be using a Vector to read the data. Then it doesn't matter is you have 10 rows of data or 100.

Using this approach the code would be something like:

Vector data = new Vector();

while ((String textLine = bf.readLine()) != null) 
    String text = textLine.split("    ");
    Vector row = new Vector();

    for (int i = 0; i < text.length; i++)
         row.addElement( text[i] );

So you would need to change the method to return the Vector of data. You would also need to change your "columnNames" to be added to a Vector so you can create the TableModel using the two Vectors.