Java Program to select a column in JTable?


To select a column in a JTable, use the setColumnSelectionInterval() and set the interval for the column you would like to select.

For example, if you want to select a single column i.e. column2, then set the interval as (2,2) in the setColumnSelectionInterval() method.

The following is an example to select a column from a table in Java −

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(), "Stock", TitledBorder.CENTER, TitledBorder.TOP));
      String[][] rec = {
         { "001", "Shirts", "40" },
         { "002", "Trousers", "250" },
         { "003", "Jeans", "25" },
         { "004", "Applicances", "90" },
         { "005", "Mobile Phones", "200" },
         { "006", "Hard Disk", "150" },
      };
      String[] header = { "ID", "Product", "Quantity" };
      JTable table = new JTable(rec, header);
      table.setShowHorizontalLines(true);
      table.setGridColor(Color.blue);
      table.setColumnSelectionAllowed(true);
      table.setRowSelectionAllowed(false);
      table.setColumnSelectionInterval(2,2);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}

This will produce the following output −

Above, we have also set the setRowSelectionAllowed() as FALSE and setColumnSelectionAllowed() as TRUE since we need to select column here.

Updated on: 30-Jul-2019

803 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements