Java JTable set single interval selection

Description

Java JTable set single interval selection

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;

public class Main extends JPanel {
   public Main() {
      super(new BorderLayout());
      String[] columnNames = { "ID", "Spanish", "Italian" };
      String[][] tableData = { //from w w  w . j a v a  2 s  . c o  m
            { "1", "uno", "uno" }, 
            { "2", "dos", "due" }, 
            { "3", "tres", "tre" },
            { "4", "cuatro", "quattro" }, 
            { "5", "cinco", "cinque" }, 
            { "6", "seis", "sei" },
            { "7", "siete", "sette" } };

      JTable table = new JTable(tableData, columnNames);
      ListSelectionModel listSelectionModel = table.getSelectionModel();
      table.setSelectionModel(listSelectionModel);
      JScrollPane tablePane = new JScrollPane(table);

      listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

      add(tablePane, BorderLayout.CENTER);
   }

   public static void main(String[] args) {
      JFrame frame = new JFrame("TableSelectionDemo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Main demo = new Main();
      demo.setOpaque(true);
      frame.setContentPane(demo);
      frame.pack();
      frame.setVisible(true);
   }
}



PreviousNext

Related