读取文本文件并在Jtable中显示?

时间:2013-04-15 08:29:39

标签: text get jtable

我需要逐行阅读文本文件的内容并在Jtable上显示,该表应该由用户根据需要编辑,任何帮助都会得到赞赏。我是Java新手。谢谢。

我的文本文件:文件名(people.txt)

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

我的代码:

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();
        }
    }
}

谢谢。

2 个答案:

答案 0 :(得分:2)

文件内容:(每个属性用分号分隔,每行都是记录。)

  

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;
            }
        }
    }
}

答案 1 :(得分:1)

好吧,我没看过你的代码...但是我告诉你这是最简单的方法之一...希望这有帮助

定义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);

从文本文件中读取:

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();

    }

此外,如果要允许用户编辑数据,则需要在希望人们编辑的单元格上设置TableCellEditor。您可能还想开始使用TableModel而不是对JTable本身中的数据进行硬编码。

请参阅http://docs.oracle.com/javase/tutorial/uiswing/components/table.html