SharedListSelectionHandler.java Source code

Java tutorial

Introduction

Here is the source code for SharedListSelectionHandler.java

Source

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);
    }
}