Java Program to enable cell selection in a JTable

Java 8Object Oriented ProgrammingProgramming

To enable cell selection, use the setCellSelectionEnabled() method and set it to TRUE −

table.setCellSelectionEnabled(true);

The above sets whether this table allows both a column selection and arow selection to exist simultaneously.

The following is an example to enable cell selection in a JTable −

Example

package my;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel();
      panel.setBorder(BorderFactory.createTitledBorder(
         BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP));
      String[][] rec = {
         { "1", "Steve", "AUS" },
         { "2", "Virat", "IND" },
         { "3", "Kane", "NZ" },
         { "4", "David", "AUS" },
         { "5", "Ben", "ENG" },
         { "6", "Eion", "ENG" },
      };
      String[] header = { "Rank", "Player", "Country" };
      JTable table = new JTable(rec, header);
      table.setShowHorizontalLines(true);
      table.setGridColor(Color.orange);
      table.setCellSelectionEnabled(true);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}

The output is as follows. Here, we have selected a single selection. We can select a cell now since setCellSelectionEnabled() is set TRUE above −


raja
Published on 03-Jun-2019 12:14:00
Advertisements