JTable

Java JTable Example

In this example we are going to demonstrate how to use Java Swing JTableJTable is a Swing component with which we can display tables of data, optionally allowing the user to edit the data, JTable relies on a separate TableModel object to hold and represent the data it displays.
This article shows how to work with JTable using a simple example where we build a GUI with a JTable to show contents of a directory in the filesystem in tabular form.

 

1. Swing JTable:

We create a new JTable object where we can initialize the data model and enable scrolling.

// Create a JTable and tell it to display our model
JTable table = new JTable(tableModel);

// Put the JTable in a JScrollPane to handle scrolling
JScrollPane tableScrollPane = new JScrollPane(table);
tableScrollPane.setPreferredSize(new Dimension(250, 200));

2. JTable Data Model:

We create a CustomTableModel.java as we want to display a tabular view of data that is not, by nature, tabular, you must implement the TableModel interface (or, more likely, subclass the AbstractTableModel class). The job of this TableModel implementation is to serve as the interface between your data, which is not neatly organized into a table, and the JTable object, which wants to display a table. In other words, your TableModel presents a neat tabular view of your data, regardless of how the data is organized underneath.

CustomTableModel.java:

package com.jcg;

import java.io.File;
import java.util.Date;

import javax.swing.table.AbstractTableModel;

/**
 * The Class CustomTableModel contains methods to allow the JTable component to
 * get and display data about the files in a specified directory. It represents
 * a table with six columns: filename, size, modification date, plus three
 * columns for flags: directory, readable, writable.
 * 
 * @author ashraf_sarhan
 */
@SuppressWarnings("serial")
public class CustomTableModel extends AbstractTableModel {

	private File dir;
	private String[] filenames;
	private String[] columnNames = TableColumn.getNames();
	private Class<?>[] columnClasses = Constants.COLUMN_CLASSES;

	// This table model works for any one given directory
	public CustomTableModel(File dir) {
		this.dir = dir;
		// Store a list of files in the directory
		this.filenames = dir.list();
	}

	// Returns a constant columns number for this model
	public int getColumnCount() {
		return Constants.COLUMN_CLASSES.length;
	}

	// Returns the number of files in directory
	public int getRowCount() {
		return filenames.length;
	}

	// Returns the name of the given column index
	public String getColumnName(int col) {
		return columnNames[col];
	}

	public Class<?> getColumnClass(int col) {
		return columnClasses[col];
	}

	// Returns the value of each cell
	public Object getValueAt(int row, int col) {
		File f = new File(dir, filenames[row]);
		TableColumn tableColumn = TableColumn.fromIndex(col);
		switch (tableColumn) {
		case NAME:
			return filenames[row];
		case SIZE:
			return new Long(f.length());
		case LAST_MODIFIED:
			return new Date(f.lastModified());
		case DIRECTORY:
			return f.isDirectory() ? Boolean.TRUE : Boolean.FALSE;
		case READABLE:
			return f.canRead() ? Boolean.TRUE : Boolean.FALSE;
		case WRITABLE:
			return f.canWrite() ? Boolean.TRUE : Boolean.FALSE;
		default:
			return null;
		}
	}

}

Also, we have an enum TableColumn.java which represents the table six columns (filename, size, modification date, directory, readable, writable).

TableColumn.java:

package com.jcg;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The Enum TableColumn contains table columns names along with their indices.
 *
 * @author ashraf_sarhan
 */
public enum TableColumn {

	NAME(0, "name"), SIZE(1, "size"), LAST_MODIFIED(2, "last modified"), DIRECTORY(
			3, "directory?"), READABLE(4, "readable?"), WRITABLE(5, "writable?");

	private TableColumn(int index, String name) {
		this.index = index;
		this.name = name;
	}

	private int index;
	private String name;

	private static final Map<Integer, TableColumn> COLUMN_INDEX_NAME_MAP = new HashMap<>();
	private static final List<String> NAMES = new ArrayList<>();

	static {
		for (TableColumn c : TableColumn.values()) {
			COLUMN_INDEX_NAME_MAP.put(c.index, c);
			NAMES.add(c.name);
		}
	}

	public static TableColumn fromIndex(int colIndex) {
		TableColumn columnName = COLUMN_INDEX_NAME_MAP.get(colIndex);
		return (columnName != null) ? columnName : null;
	}

	public static String[] getNames() {
		return NAMES.toArray(new String[NAMES.size()]);
	}

}

3. JTable Demo:

We create SwingJTableDemo.java class to test our example. Also, we add a supplementary Constants.java class contains constants used through our code.

SwingJTableDemo.java:

package com.jcg;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

/**
 * The Class SwingJTableDemo to show our running example.
 *
 * @author ashraf_sarhan
 */
public class SwingJTableDemo {

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					// Set Nimbus as L&F
					setLookAndFeel(Constants.NIMBUS_LF);
					createAndShowGUI(args);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public static void createAndShowGUI(String[] args) throws Exception {
		// Figure out what directory to display
		File dir;
		if (args.length > 0)
			dir = new File(args[0]);
		else
			dir = new File(System.getProperty("user.home"));

		// Create a TableModel object to represent the contents of the directory
		CustomTableModel tableModel = new CustomTableModel(dir);

		// Create a JTable and tell it to display our model
		JTable table = new JTable(tableModel);

		// Put the JTable in a JScrollPane to handle scrolling
		JScrollPane tableScrollPane = new JScrollPane(table);
		tableScrollPane.setPreferredSize(new Dimension(250, 200));

		JTextField dirPathTextField = new JTextField(26);

		// Create an action listener to display the given directory
		JButton displayDirButton = new JButton("Display Directory");
		displayDirButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String dirPath = dirPathTextField.getText();
				if (dirPath != null && !"".equals(dirPath)) {
					File newDir = new File(dirPath);
					;
					CustomTableModel newTableModel = new CustomTableModel(
							newDir);
					table.setModel(newTableModel);
				} else {
					JOptionPane.showMessageDialog(null,
							"Directory path is empty", "Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		});

		JPanel ctrlPane = new JPanel();
		ctrlPane.add(dirPathTextField);
		ctrlPane.add(displayDirButton);

		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
				ctrlPane, tableScrollPane);
		splitPane.setDividerLocation(35);
		splitPane.setEnabled(false);

		// Display it all in a scrolling window and make the window appear
		JFrame frame = new JFrame("Swing JTable Demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.add(splitPane);
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
	}

	public static void setLookAndFeel(String lf) throws Exception {
		try {
			for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
				if (lf.equals(info.getName())) {
					UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (Exception e) {
			// If the given lf is not available, you can set the GUI the system
			// default L&F.
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}
	}

}

Constants.java:

package com.jcg;

import java.util.Date;

/**
 * The Class Constants contains some constants which will be used across the
 * code.
 *
 * @author ashraf_sarhan
 */
public class Constants {

	public static final Class<?>[] COLUMN_CLASSES = new Class[] { String.class,
			Long.class, Date.class, Boolean.class, Boolean.class, Boolean.class };

	public static final String NIMBUS_LF = "Nimbus";

}

Output:

Figure 1: Swing JTable Demo
Figure 1: Swing JTable Demo

4. Download the Source Code of this example:

This was an example on how to use Java Swing JTable.

Download
You can download the full source code of this example here: SwingJTableExampleCode.zip

Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button