By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,649 Members | 2,142 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,649 IT Pros & Developers. It's quick & easy.

How to add data to JTable from a .txt file.

P: 14
Hello friends,

How to add data to JTable from a .txt file.

I had seen this code from one of the tutorial from java.com. This code doesnt take any input. But shows what is written in the array.

But i want the table to display the data from a .txt file in which i had stored information in this format. Can anyone please modify the codes and explain me.

Name:Mr.xyz
Phone:111111222222
Birth Date:3/3/08

Name:Mr.abc
Phone:11111133333
Birth Date:4/4/07

I tried it my self using FileReader and then storing it into an array . But the error comes when I feed the array in rows and columns.


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.Dimension;
import java.awt.GridLayout;

/**
* TableDemo is just like SimpleTableDemo, except that it
* uses a custom TableModel.
*/
public class TableDemo extends JPanel {
private boolean DEBUG = false;

public TableDemo() {
super(new GridLayout(1,0));

JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);

//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);

//Add the scroll pane to this panel.
add(scrollPane);
}

class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
private Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath",
"Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)},
{"Philip", "Milne",
"Pool", new Integer(10), new Boolean(false)},
{"Isaac", "Rabinovitch",
"Nitpicking", new Integer(1000), new Boolean(false)}
};

public int getColumnCount() {
return columnNames.length;
}

public int getRowCount() {
return data.length;
}

public String getColumnName(int col) {
return columnNames[col];
}

public Object getValueAt(int row, int col) {
return data[row][col];
}

/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}

/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
Jul 9 '08 #1
Share this Question
Share on Google+
5 Replies


Dököll
Expert 100+
P: 2,364
What is the error you are getting? It looks like it should work just fine...
Jul 12 '08 #2

P: 14
What is the error you are getting? It looks like it should work just fine...
I am Not getting any error from it but i want to know how to add data into the JTable from a .txt file
Jul 12 '08 #3

Expert 10K+
P: 11,448
I am Not getting any error from it but i want to know how to add data into the JTable from a .txt file
I think your problem is just how to read data from a file and stick that data in a
couple of arrays. What have you done already except copy a working example?

kind regards,

Jos
Jul 12 '08 #4

P: 14
I think your problem is just how to read data from a file and stick that data in a
couple of arrays. What have you done already except copy a working example?

kind regards,

Jos
Till now I tried many alternative ways to make the program work. I wrote this program and thought it will work but this gives run time error( nullpointer exception)

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.table.*;
class phoneDir
{
private Object data[][];//making it global
private JPanel GuiContent()//this will create my content pane
{
JPanel bottomPanel=new JPanel();//the bottom most panel which will hold everything
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEADING,7,7));

JTable Table=table();//this is a method which will return a JTable by filling it with data
JScrollPane scrollPane=new JScrollPane(Table);
scrollPane.setPreferredSize(new Dimension(700,300));

bottomPanel.add(scrollPane);

bottomPanel.setOpaque(true);
return bottomPanel;
}


private JTable table()//this method will create a JTable filling it with information and return the JTable
{
int count=0;//this int will count the number of lines in the file.
String title[]={"Name","Phone Number","Birth Date"};//these are the column names
try
{
InputStreamReader isr=new InputStreamReader(System.in);
FileReader fr=new FileReader("D:\\database.txt");//this is my database file
BufferedReader br=new BufferedReader(fr);

while(br.readLine()!=null)//this loop will count the number of lines in the file
{
count+=1;
}
String [][]data=new String[count/3][3];//I am making an array ehich will contain 3 columns and count/3 rows.


fr=new FileReader("D:\\database.txt");//this time i will store the data from the file to an Array
br=new BufferedReader(fr);

for(int i=0;i<count/3;i++)//this loop will store the data

{
for(int j=0;j<3;j++)
{
data[i][j]=br.readLine();
}
}
br.close();
}//end try block
catch(IOException e)
{
e.printStackTrace();
}

Vector rows=new Vector();// creating a row vector
Vector columns= new Vector();//creating a column vector
DefaultTableModel tabModel=new DefaultTableModel();
tabModel.setDataVector(rows,columns);
JTable tempTable=new JTable(tabModel);


for (int i=0;i<count/3;i++)//This loop will fill data in the table
{
for(int j=0;j<3;j++)
{
columns.addElement((String) title[i]);
rows.addElement((String) data[i][j]);
}
}

return tempTable;
}//end of table()


private static void createGui()
{
JFrame frame=new JFrame("My Phone Directory");
phoneDir obj=new phoneDir();
frame.setContentPane(obj.GuiContent());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
frame.setSize(1000,650);
frame.setVisible(true);
frame.setLocation(10,10);
}

public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){public void run() {createGui();}});
}
}



Please reply if anybody can remove the nullpointer Exception
Jul 13 '08 #5

Expert 10K+
P: 11,448
Please reply if anybody can remove the nullpointer Exception
You'd better remove and rewrite that entire table() method because it's a mess.
First you're reading all the data in a (two dimensional) array and then you're
trying to haul everything over to vectors (of the incorrect format) whith which
you're trying to fool a DefaultTableModel.

Read the API documentation of the DefaultTableModel class again. The third
constructor is the one you need; it does everything for you: you feed it an
Object[][] data matrix and an Object[] header row; (so no String[][] nor String[])

All the vector juggling can go. It is totally wrong anyway. Come back here if
you're having trouble with it. Try to print out the values of your data matrix and
see if it was read correctly from your file (I guess it is, so you're almost ready).

kind regards,

Jos
Jul 13 '08 #6

Post your reply

Sign in to post your reply or Sign up for a free account.