0

i need to read the contents of text file, line by line and display it on the Jtable, the table should be editable by users as needed, Any help Appreciated. I am new to Java. Thank You.

My Text File: File Name(people.txt)

COLUMN_NAME COLUMN_TYPE IS_NULLABLE COLUMN_KEY  COLUMN_DEFAULT  EXTRA   
Names   VARCHAR(500)    NO  
Address VARCHAR(500)    NO

My Code So Far:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class readtext {
    static public void main(String[] arg){
        JScrollPane scroll;
        JTable table;
        DefaultTableModel model;
        String fname="people";
        try
        {
            FileInputStream fstream = new FileInputStream("D:/joy/text/"+fname+".txt");


            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine,str = null;
            //Read File Line By Line
            String text = "";
            Vector myVector = new Vector();
            while ((strLine = br.readLine()) != null) //loop through each line
            {
                myVector.add(strLine );
                // Print the content on the console
                text +=(strLine+"\n");  // Store the text file in the string
            }
            in.close();//Close the input stream
            int i=0;
            String fline=myVector.elementAt(0).toString();
            String[] sp=fline.split("\\s+");
            for(String spt:sp){
                System.out.println(spt);
                //model = new DefaultTableModel(spt, );   // I dont know how to put the strings
                into Jtable here
                table = new JTable(){
                    public boolean isCellEditable(int row, int column){
                        return false;
                    }
                };
                int a=0;// for text box name
                for(i=1;i<myVector.size();i++){
                    str=myVector.elementAt(i).toString();
                    String[] res =str.split("\\s+");
                    int k=0;
                    for(String st:res)
                    System.out.println(st);
                k++;a++; }
        } }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

Thank You.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
Shaiju T
  • 6,201
  • 20
  • 104
  • 196
  • Read each line. Separate them using a delimiter and then store each one in the respective attribute of the `Data Object` Add each one to the list and finally add the list to the `TableModel` – Amarnath Apr 15 '13 at 13:51
  • can you show me a example , i AM not familiar with Jtable – Shaiju T Apr 17 '13 at 05:05

2 Answers2

4

File Content: (Each attribute is separated by a semicolon and each line is a record.)

Hello1;123

World1;234

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class FileToJTable {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            public void run() {
                new FileToJTable().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

    private void createUI() {

        try {
            JFrame frame = new JFrame();
            frame.setLayout(new BorderLayout());
            JTable table = new JTable();

            String readLine = null;

            StudentTableModel tableModel = new StudentTableModel();
            File file = new File(""/*Give your File Path here*/);

            FileReader reader = new FileReader(file);
            BufferedReader bufReader = new BufferedReader(reader);

            List<Student> studentList = new ArrayList<Student>();
            while((readLine = bufReader.readLine()) != null) {
                String[] splitData = readLine.split(";");

                Student student = new Student();
                student.setName(splitData[0]);
                student.setNumber(splitData[1]);

                studentList.add(student);
            }

            tableModel.setList(studentList);
            table.setModel(tableModel);

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new JScrollPane(table));
            frame.setTitle("File to JTable");
            frame.pack();
            frame.setVisible(true);

        } catch(IOException ex) {}
    }

    class Student {

        private String name;
        private String number;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getNumber() {
            return number;
        }
        public void setNumber(String number) {
            this.number = number;
        }
    }

    class StudentTableModel extends AbstractTableModel {

        private List<Student> list = new ArrayList<Student>();
        private String[] columnNames = {"Name", "Number"};

        public void setList(List<Student> list) {
            this.list = list;
            fireTableDataChanged();
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        public int getRowCount() {
            return list.size();
        }

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

        public Object getValueAt(int rowIndex, int columnIndex) {
            switch (columnIndex) {
            case 0:
                return list.get(rowIndex).getName();
            case 1:
                return list.get(rowIndex).getNumber();
            default:
                return null;
            }
        }
    }
}
Amarnath
  • 8,736
  • 10
  • 54
  • 81
  • hi che thanks for the code, but can you do it according to my text file, so far i have done this: http://stackoverflow.com/questions/16052821/format-the-jtable-as-shown-in-text-file – Shaiju T Apr 17 '13 at 06:19
  • @tim Only parsing the file is different. Try it out it is easy. Learn how to split data using delimiters. – Amarnath Apr 17 '13 at 09:46
1

Well i didnt read ur code...however i'm telling u one of the simplest way of doing this...hope this helps

Define a DefaultTableModel:

String columns[] =  {  //Column Names// };
    JTable contactTable = new JTable();
    DefaultTableModel tableModel;
    // specify number of columns
    tableModel = new DefaultTableModel(0,2); 
    tableModel.setColumnIdentifiers(columns);
    contactTable.setModel(tableModel);

Reading from text file:

String line;
BufferedReader reader;
    try{       
        reader = new BufferedReader(new FileReader(file));
        while((line = reader.readLine()) != null) 
        {
           tableModel.addRow(line.split(", ")); 
        }
        reader.close();
     }
    catch(IOException e){
        JOptionPane.showMessageDialog(null, "Error");
e.printStackTrace();

    }

Also, if you want to allow users to edit the data, then you need to set a TableCellEditor on the cells that you want people to edit. You probably also want to start using a TableModel instead of hard coding the data in the JTable itself.

See http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

Vinayak Pahalwan
  • 2,915
  • 4
  • 26
  • 34