Java ListSelectionModel is selection empty

Description

Java ListSelectionModel is selection empty

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

class My implements ListSelectionListener {
   public void valueChanged(ListSelectionEvent e) {
      ListSelectionModel lsm = (ListSelectionModel) e.getSource();

      int firstIndex = e.getFirstIndex();
      int lastIndex = e.getLastIndex();
      boolean isAdjusting = e.getValueIsAdjusting();
      System.out.println("Event for indexes " + firstIndex + " - " + lastIndex + "; isAdjusting is " + isAdjusting
            + "; selected indexes:");

      if (lsm.isSelectionEmpty()) {
         System.out.println(" <none>");
      } else {// www  .j  av  a  2 s  .com
         // Find out which indexes are selected.
         int minIndex = lsm.getMinSelectionIndex();
         int maxIndex = lsm.getMaxSelectionIndex();
         for (int i = minIndex; i <= maxIndex; i++) {
            if (lsm.isSelectedIndex(i)) {
               System.out.println(" " + i);
            }
         }
      }
   }
}

public class Main {
   public static void main(String args[]) {
      JFrame frame = new JFrame("java2s.com");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      String[] columnNames = { "ID", "Spanish", "Italian" };
      String[][] tableData = { //
            { "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);
      table.getSelectionModel().addListSelectionListener(new My());
      JScrollPane scrollPane1 = new JScrollPane(table);
      frame.add(scrollPane1, BorderLayout.CENTER);

      frame.setSize(640, 300);
      frame.setVisible(true);
   }
}



PreviousNext

Related