How to Get Selected Value from JTable in Java
JTable is a flexible Swing component that is very well suited to display data in a tabular format. In this tutorial, we are going to see how to get selected values from JTable in Java.
Each time a selection is made, ListSelectionEvent is triggered. The valueChanged() method in the ListSelectionListener interface is called each time a new selection has been made.
Java Program to Get Selected Value from JTable:
import javax.swing.*; import java.awt.*; import javax.swing.table.*; import javax.swing.event.*; import java.awt.event.*; public class SelectedValJTable implements ListSelectionListener { JTable table; public SelectedValJTable() { JFrame f = new JFrame("Get Selected Value From JTable"); //JTable Headers String[] columns = new String[] { "Id", "Name", "Address", "Hourly rate" }; //data for JTable in a 2D table Object[][] data = new Object[][] { {1, "Thomas", "Alaska", 20.0 }, {2, "Jean", "Arizona", 50.0 }, {3, "Yohan", "California", 30.0 }, {4, "Emily", "Florida", 60.0 }, {5, "Alex", "Boston", 10.0 }, }; //set the TableModel to get data from JTable TableModel model = new AbstractTableModel() { public int getColumnCount() { return columns.length; } public int getRowCount() { return data.length; } public Object getValueAt(int row, int col) { return data[row][col]; } public String getColumnName(int column) { return columns[column]; } public Class getColumnClass(int col) { return getValueAt(0,col).getClass(); } public void setValueAt(Object aValue, int row, int column) { data[row][column] = aValue; } }; table = new JTable(model); ListSelectionModel listModel = table.getSelectionModel(); listModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listModel.addListSelectionListener(this); JScrollPane scroll = new JScrollPane(table); scroll.setPreferredSize(new Dimension(300, 300)); f.getContentPane().add(scroll); f.setSize(400, 180); f.setVisible(true); } public void valueChanged(ListSelectionEvent e) { int[] sel; Object value; if (!e.getValueIsAdjusting()) { sel = table.getSelectedRows(); if (sel.length > 0) { for (int i=0; i < 4; i++) { // get data from JTable TableModel tm = table.getModel(); value = tm.getValueAt(sel[0],i); System.out.print(value + " "); } System.out.println(); } } } public static void main(String[] args) { new SelectedValJTable(); } }
Output: