Home Tutorial Java Core Files Java insert file data to JTable

 
 

Share on Google+Share on Google+
Java insert file data to JTable
Posted on: June 12, 2006 at 12:00 AM
Advertisement
In this section, you will learn how to insert text file data into JTable.

Java insert file data to JTable

In this section, you will learn how to insert text file data into JTable.

Swing has provide useful and sophisticated set of GUI components. It provides a native look and feel that emulates the look and feel of several platforms. In the given example, we have used these components.

You can see in the given example, we have extended our class with AbstractTableModel to inherit its methods and properties. Now we have read the file and store the data into vector. Then pass the vector value as a parameter to the  JTable class.

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

 Through the above code, you can insert the file data into JTable.

Advertisement

Related Tags for Java insert file data to JTable:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 12, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com