Allowing only individual rows to be selected in a JTable

By default, multiple rows can be selected in a Table. You can change this behavior through a ListSelectionModel. Invoke the method setSelectionMode on your JTable object and set it to one of these three static final variables defined in ListSelectionModel:

MULTIPLE_INTERVAL_SELECTION: to allow multiple contiguous selection ranges
SINGLE_INTERVAL_SELECTION: to allow one contiguous selection range
SINGLE_SELECTION: to allow only one list index selection

Add a ListSelectionListener and define the behaviour in valueChanged.

Here’s a working example:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame 
   public Main() {
      super("Table example, Wines from Bordeaux");
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      String columnheaders[] = { "Wine", "Vintage", "Price" };
      JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      JScrollPane scrollPane = new JScrollPane(table);
      ListSelectionModel listSelectionModel = table.getSelectionModel();
      listSelectionModel.addListSelectionListener(new ListSelectionListener() {
         public void valueChanged(ListSelectionEvent e) {
            // ignore clicks when user is still making his selection,
            // eg. dragging the mouse
            if (e.getValueIsAdjusting()) return;
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();
            if (lsm.isSelectionEmpty()) {
               System.out.println("No selection!");
            } else {
               int selectedRow = lsm.getMinSelectionIndex();
               System.out.println("Row selected: " + selectedRow);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
   public static void main(String []args) {
      Main main = new Main();;