JTable in Java Swing

In this post, we will create a JFrame and add a JPanel to it. We will then create a DefaultTableModel and add some rows to it. After that, we will create a JTable and set its model to the table model, and then add the table to the panel using a JScrollPane. We then add the panel to the frame and show the frame.

Let’s see an example code below:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class JTableDemo extends JFrame {

	private JPanel panel;
	private JTable table;

	public JTableDemo() {
        // Set the frame properties
        setTitle("JTable Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 300);

        // Create the panel
        panel = new JPanel();

        // Create the table model and set the column names
        String[] columnNames = {"Name", "Age", "Gender"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);

        // Add some rows to the table model
        Object[] rowData1 = {"Sachin Tendulkar", 47, "Male"};
        Object[] rowData2 = {"MS Dhoni", 39, "Male"};
        Object[] rowData3 = {"Yuvraj Singh", 39, "Male"};
        tableModel.addRow(rowData1);
        tableModel.addRow(rowData2);
        tableModel.addRow(rowData3);

        // Create the table and set the table model
        table = new JTable(tableModel);

        // Add the table to the panel
        panel.add(new JScrollPane(table));

        // Add the panel to the frame
        add(panel);

        // Show the frame
        setVisible(true);
    }

	public static void main(String[] args) {
		new JTableDemo();
	}

}

When we run this code, it will display a JFrame with a JTable showing the data like the below:

JTable output

Add data dynamically

In the earlier example, we’ve added data one by one. Now, we can create a list of objects that holds the data and iterate over for loop to add data to the table model dynamically.

List<Object[]> cricketers = Arrays.asList(
		new Object[] { "Sachin Tendulkar", 47, "Male" },
		new Object[] { "MS Dhoni", 39, "Male" }, 
		new Object[] { "Yuvraj Singh", 39, "Male" },
		new Object[] { "Smriti Mandhana", 24, "Female" });

for (Object[] cricketer : cricketers) {
	tableModel.addRow(cricketer);
}

How to get the selected row value in JTable

To get the selected row data in a JTable using Java Swing, we need to follow the steps given below:

  1. Get the JTable object that we want to retrieve the selected row data from.
  2. Call the getSelectedRow() method on the JTable object to get the index of the selected row.
  3. Call the getValueAt() method on the JTable object, passing in the row index and the column index, to get the value of the selected cell.
  4. Repeat step 3 for each column to retrieve all the data from the selected row.

Following is the code snippet of the above steps:

JTable table = new JTable(); // replace with your own JTable object
int selectedRow = table.getSelectedRow();
if (selectedRow != -1) { // make sure a row is actually selected
    String col1Value = table.getValueAt(selectedRow, 0).toString();
    String col2Value = table.getValueAt(selectedRow, 1).toString();
    // repeat for other columns as needed
    System.out.println("Selected row data: " + col1Value + ", " + col2Value);
}

The actual working code is given below along with its output.

Complete example:

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Arrays;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class JTableDemo extends JFrame {

	private JPanel panel;
	private JTable table;

	public JTableDemo() {
		// Set the frame properties
		setTitle("JTable Example");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(500, 300);

		// Create the panel
		panel = new JPanel();

		// Create the table model and set the column names
		String[] columnNames = { "Name", "Age", "Gender" };
		DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);

		List<Object[]> cricketers = Arrays.asList(new Object[] { "Sachine Tendulkar", 47, "Male" },
				new Object[] { "MS Dhoni", 39, "Male" }, new Object[] { "Yuvraj Singh", 39, "Male" },
				new Object[] { "Smriti Mandhana", 24, "Female" });

		for (Object[] cricketer : cricketers) {
			tableModel.addRow(cricketer);
		}

		// Create the table and set the table model
		table = new JTable(tableModel);

		// Add the table to the panel
		panel.add(new JScrollPane(table));

		// Add the panel to the frame
		add(panel);

		// Show the frame
		setVisible(true);

		displaySelectedRowData(table);

	}

	private void displaySelectedRowData(JTable table) {

		table.addMouseListener(new MouseListener() {

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseClicked(MouseEvent e) {

				int selectedRow = table.getSelectedRow();
				if (selectedRow != -1) { // make sure a row is actually selected
					String name = table.getValueAt(selectedRow, 0).toString();
					String age = table.getValueAt(selectedRow, 1).toString();
					String gender = table.getValueAt(selectedRow, 2).toString();
					// repeat for other columns as needed
					System.out.println("Selected row data: " + name + ", " + age + ", " + gender);
				}

			}
		});
	}

	public static void main(String[] args) {
		new JTableDemo();
	}

}

Output:

How to get selected row's data JTable in Java Swing

When a user clicks on the row of the JTable, it prints the output on the console like the below:

Selected row data: Smriti Mandhana, 24, Female
Selected row data: Yuvraj Singh, 39, Male
Selected row data: MS Dhoni, 39, Male
Selected row data: Sachine Tendulkar, 47, Male

The output above is generated when I click on the row each time. Hence, each output row is one mouse click.

Note: In the above code, I’ve implemented only one method from the MouseListener interface and others are not used. If you want to use others’ events then you can. Normally, we use an adapter class and override only the required method so that the code looks cleaner.

There are many properties in the JTable and it is not possible to cover everything. You can follow the official documents for more detail.

Reference: https://docs.oracle.com/javase/tutorial/uiswing/components/table.html

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments