Java Program to retrieve the value from a cell in a JTable


To retrieve the value of a cell, use the getValueAt() method. As parameters, set the row and column index value for which you want the cell value −

int rIndex = 5; // row index
int cIndex = 1; // column index
Object ob = table.getValueAt(rIndex, cIndex);

Display the cell value in the Console −

System.out.println("Value = "+ob);

The following is an example to retrieve the value from a cell −

Example

package my;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      JFrame frame = new JFrame("Demo");
      JPanel panel = new JPanel();
      String data[][] = {
         {"Australia","5","1"},
         {"US","10","2"},
         {"Canada","9","3"},
         {"India","7","4"},
         {"Poland","2","5"},
         {"SriLanka","5","6"}
      };
      String col [] = {"Team","Selected Players","Rank"};
      DefaultTableModel tableModel = new DefaultTableModel(data,col);
      JTable table = new JTable(tableModel);
      table.getTableHeader().setResizingAllowed(false);
      Dimension dim = new Dimension(50,2);
      table.setIntercellSpacing(new Dimension(dim));
      int rIndex = 5; // row index
      int cIndex = 1; // column index
      Object ob = table.getValueAt(rIndex, cIndex);
      System.out.println("Value = "+ob);
      JScrollPane scrollPane = new JScrollPane(table);
      panel.add(scrollPane);
      frame.add(panel);
      frame.setSize(600,400);
      frame.setUndecorated(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getRootPane().setWindowDecorationStyle(JRootPane.COLOR_CHOOSER_DIALOG);
      frame.setVisible(true);
   }
}

Output

The value of the cell is displayed in the console −


Updated on: 30-Jul-2019

841 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements