Tuesday, March 30, 2010

Enabling a Row or a Column Selection in JTable (SWING)

In this example I’m going to discuss about how to select one whole row or a column when a cell in a JTable is clicked. It’s not something hard, since it just requires 3 lines of code to be included. Follow the steps below to make it happen.
Steps:
  1. Since we are just going to select one particular row or column in a JTable, the selection mode has to be set as Single selection using the constants in ListSelection Model Interface. E.g: jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  2. If row selection is to be enabled, set the row selection method as “true” and column selection method as false”. Code snippet and output are as below.

  3. If column selection is to be enabled, set the row selection method as “false” and column selection method as “true”. Code snippet and output are as below.

Author: Thiagu