Java Swing How to - Make JTable single selectable








Question

We would like to know how to make JTable single selectable.

Answer

import java.awt.BorderLayout;
/*w w  w.j  a  v  a  2 s . c o m*/
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;

public class Main {
  public static void main(String args[]) {

    final Object rowData[][] = { { "1", "one", "I" }, { "2", "two", "II" }, { "3", "three", "III" } };
    final String columnNames[] = { "#", "English", "Roman" };

    final JTable table = new JTable(rowData, columnNames);
    JScrollPane scrollPane = new JScrollPane(table);

    JFrame frame = new JFrame("Resizing Table");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(scrollPane, BorderLayout.CENTER);

    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    frame.setSize(300, 150);
    frame.setVisible(true);

  }
}