Shared ListSelectionHandler : ListSelectionListener « Swing Event « Java Tutorial






Shared ListSelectionHandler
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 SharedListSelectionHandler 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 {
      // 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 AddingTableSelectionListener {
  static String labels[] = { "A", "B", "C", "D", "E", "F", "G" };

  public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    String[] columnNames = { "French", "Spanish", "Italian" };
    String[][] tableData = { { "un", "uno", "uno" }, { "deux", "dos", "due" },
        { "trois", "tres", "tre" }, { "quatre", "cuatro", "quattro" },
        { "cinq", "cinco", "cinque" }, { "six", "seis", "sei" }, { "sept", "siete", "sette" } };

    JTable table = new JTable(tableData, columnNames);
    table.getSelectionModel().addListSelectionListener(new SharedListSelectionHandler());
    JScrollPane scrollPane1 = new JScrollPane(table);
    frame.add(scrollPane1, BorderLayout.CENTER);

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








15.24.ListSelectionListener
15.24.1.Listening to JList Events with a ListSelectionListenerListening to JList Events with a ListSelectionListener
15.24.2.Shared ListSelectionHandlerShared ListSelectionHandler
15.24.3.ListSelectionEvent
15.24.4.ListSelectionListener and ListSelectionEvent
15.24.5.ListSelectionModel, JTable and ListSelectionListener
15.24.6.ListSelectionModel and ListSelectionListener
15.24.7.Implement a graphical list selection monitor