473,407 Members | 2,306 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

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

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
5 9743
Dököll
2,364 Expert 2GB
What is the error you are getting? It looks like it should work just fine...
Jul 12 '08 #2
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
JosAH
11,448 Expert 8TB
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
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
JosAH
11,448 Expert 8TB
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

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

Similar topics

1
by: asd | last post by:
I need to make the cells in the 1st column look like the column header. I tried the following code but it didn't change anything: private void rendererTest() { TableColumn column =...
1
by: raysaun | last post by:
I am trying to set a TableCellEditor for a JTable, however, the editor never seems to get called. I can not even get a simplified version (below) to work. When I put a breakpoint on the return...
0
by: nuria | last post by:
hi, I have an editable JTable, when you are editing it and press F8 shows a dialog and then go again to the JTable window but the focus goes to a JtextField component, go with the tab for the...
1
by: onsir | last post by:
I have code like this, but still wrong. how to show data from database in JTable. package my.JavaNetBean; import java.sql.*; import java.io.*; import java.sql.Connection; import...
5
by: Ahmed Osama | last post by:
I'm using NetBeans 5.5 First :I want to bind data from table from MS Access DB into JTable . Second: Is there any other component in java to do the previous action(e.g. DataGrid )
2
by: renehv | last post by:
Hi, does somebody konws how in runtime execution to change the data values in a JTable, setValueAt works only if the change is in the same table , if i want to change the table values from another...
16
by: Epix | last post by:
Hi, I have a program that is written in Java using swing. There is a JTable that is filled with data that needs to be put into a table on a web site which is written in Javascript. Each cell in...
1
by: rengaraj | last post by:
Hi dears! I have some questions about JTable: 1- how can set some columns of my table in editable mode and som uneditable? 2- how can I create in some columns controls such as JButton or...
5
by: rburke1125 | last post by:
Hello All! I'm a bit new to Java, and certainly to the community. I'd appreciate any and all pointers to the right direction! I have a JTable that I have populated with a 2 dimensional array. ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.