Extract File data into JTable


 

Extract File data into JTable

In this section, you will learn how to read the data from the text file and insert it into JTable.

In this section, you will learn how to read the data from the text file and insert it into JTable.

Extract File data into JTable

In this section, you will learn how to read the data from the text file and insert it into JTable. For this, we have created a java class that extends the AbstractTableModel which provides default implementations for most of the methods in the TableModel interface. Using the BufferedReader class, we have read the data of the file. This data is then broken into tokens using StringTokenizer class.These token are then stored in Vector and displayed on the table.

Here is the student.txt:

Id  Name  Course  Department

1   A       MCA   ComputerScience

2   B       Btech   Mechanical

3   C       Btech   Electrical

4   D       MBA   Management



Here is the code:

import java.io.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;

public class InsertFileDataToJTable extends AbstractTableModel {
	Vector data;
	Vector columns;

	public InsertFileDataToJTable() {
		String line;
		data = new Vector();
		columns = new Vector();
		try {
			FileInputStream fis = new FileInputStream("student.txt");
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
			while (st1.hasMoreTokens())
				columns.addElement(st1.nextToken());
			while ((line = br.readLine()) != null) {
				StringTokenizer st2 = new StringTokenizer(line, " ");
				while (st2.hasMoreTokens())
					data.addElement(st2.nextToken());
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int getRowCount() {
		return data.size() / getColumnCount();
	}

	public int getColumnCount() {
		return columns.size();
	}

	public Object getValueAt(int rowIndex, int columnIndex) {
		return (String) data.elementAt((rowIndex * getColumnCount())
				+ columnIndex);
	}

	public static void main(String s[]) {
		InsertFileDataToJTable model = new InsertFileDataToJTable();
		JTable table = new JTable();
		table.setModel(model);
		JScrollPane scrollpane = new JScrollPane(table);
		JPanel panel = new JPanel();
		panel.add(scrollpane);
		JFrame frame = new JFrame();
		frame.add(panel, "Center");
		frame.pack();
		frame.setVisible(true);
	}
}

Output:

In this tutorial we have learned to display data into Swing table.

Ads