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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • moizpalitanawala
    New Member
    • Jul 2008
    • 14

    #1

    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:111111222 222
    Birth Date:3/3/08

    Name:Mr.abc
    Phone:111111333 33
    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.JFr ame;
    import javax.swing.JPa nel;
    import javax.swing.JSc rollPane;
    import javax.swing.JTa ble;
    import javax.swing.tab le.AbstractTabl eModel;
    import java.awt.Dimens ion;
    import java.awt.GridLa yout;

    /**
    * 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.setPrefer redScrollableVi ewportSize(new Dimension(500, 70));
    table.setFillsV iewportHeight(t rue);

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

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

    class MyTableModel extends AbstractTableMo del {
    private String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian "};
    private Object[][] data = {
    {"Mary", "Campione",
    "Snowboardi ng", 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", "Rabinovitc h",
    "Nitpicking ", new Integer(1000), new Boolean(false)}
    };

    public int getColumnCount( ) {
    return columnNames.len gth;
    }

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

    public String getColumnName(i nt 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;
    }
    }
  • Dököll
    Recognized Expert Top Contributor
    • Nov 2006
    • 2379

    #2
    What is the error you are getting? It looks like it should work just fine...

    Comment

    • moizpalitanawala
      New Member
      • Jul 2008
      • 14

      #3
      Originally posted by Dököll
      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

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by moizpalitanawal a
        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

        Comment

        • moizpalitanawala
          New Member
          • Jul 2008
          • 14

          #5
          Originally posted by JosAH
          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.tab le.*;
          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.set Layout(new FlowLayout(Flow Layout.LEADING, 7,7));

          JTable Table=table();//this is a method which will return a JTable by filling it with data
          JScrollPane scrollPane=new JScrollPane(Tab le);
          scrollPane.setP referredSize(ne w Dimension(700,3 00));

          bottomPanel.add (scrollPane);

          bottomPanel.set Opaque(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","Pho ne Number","Birth Date"};//these are the column names
          try
          {
          InputStreamRead er isr=new InputStreamRead er(System.in);
          FileReader fr=new FileReader("D:\ \database.txt") ;//this is my database file
          BufferedReader br=new BufferedReader( fr);

          while(br.readLi ne()!=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(IOExcepti on e)
          {
          e.printStackTra ce();
          }

          Vector rows=new Vector();// creating a row vector
          Vector columns= new Vector();//creating a column vector
          DefaultTableMod el tabModel=new DefaultTableMod el();
          tabModel.setDat aVector(rows,co lumns);
          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.addElem ent((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.setConten tPane(obj.GuiCo ntent());
          frame.setDefaul tCloseOperation (JFrame.EXIT_ON _CLOSE);
          frame.setSize(1 000,650);
          frame.setVisibl e(true);
          frame.setLocati on(10,10);
          }

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



          Please reply if anybody can remove the nullpointer Exception

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #6
            Originally posted by moizpalitanawal a
            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 DefaultTableMod el.

            Read the API documentation of the DefaultTableMod el 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

            Comment

            Working...