Java Swing GUI

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[] {
         "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();

    JScrollPane scroll = new JScrollPane(table);
    scroll.setPreferredSize(new Dimension(300, 300));
    f.setSize(400, 180);

  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 + " ");

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


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *