How to select different cells of a JTable programmatically in Java?

JavaObject Oriented ProgrammingProgramming

A JTable is a subclass of JComponent class and it can be used to create a table with information displayed in multiple rows and columns. When a value is selected from a JTable, a TableModelEvent is generated, which is handled by implementing a TableModelListener interface.

In general, a user can select the rows and columns manually in a JTable, we can also select different cells of a JTable programmatically using setRowSelectionInterval() and setColumnSelectionInterval() methods of JTable class.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTableCellSelectionTest extends JFrame {
   private JTable table;
   public JTableCellSelectionTest() {
      setTitle("JTableCellSelection Test");
      Object[][] data = {{ "Raja", "Java", "Hyderabad"}, {"Vineet", "JavaScript", "Bangalore"},
                         {"Adithya", "Scala", "Chennai"}, {"Jai", "ServiceNow", "Pune"},
                         {"Chaitanya", "Python", "Noida"}, {"Krishna", "AI", "Mumbai"}};

      String columns[] = {"Name", "Technology", "Location"};
      table = new JTable(data, columns);
      add(new JScrollPane(table));
      table.setRowSelectionInterval(0, 2);
      table.setColumnSelectionInterval(0, 2);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String []args) {
      new JTableCellSelectionTest();
   }
}

Output


raja
Published on 19-Aug-2019 16:02:04
Advertisements