In this example we are going to see how to use Java JList Events With ListSelectionListener.
Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class Main { public static void main(String args[]) { String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H" }; JFrame frame = new JFrame("Selecting JList"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JList jlist = new JList(labels); JScrollPane scrollPane1 = new JScrollPane(jlist); frame.add(scrollPane1, BorderLayout.CENTER); ListSelectionListener listSelectionListener = new ListSelectionListener() { public void valueChanged(ListSelectionEvent listSelectionEvent) { System.out.println("First index: " + listSelectionEvent.getFirstIndex()); System.out.println(", Last index: " + listSelectionEvent.getLastIndex()); boolean adjust = listSelectionEvent.getValueIsAdjusting(); System.out.println(", Adjusting? " + adjust); if (!adjust) { JList list = (JList) listSelectionEvent.getSource(); int selections[] = list.getSelectedIndices(); Object selectionValues[] = list.getSelectedValues(); for (int i = 0, n = selections.length; i < n; i++) { if (i == 0) { System.out.println(" Selections: "); } System.out.println(selections[i] + "/" + selectionValues[i] + " "); } } } }; jlist.addListSelectionListener(listSelectionListener); frame.setSize(350, 200); frame.setVisible(true); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
First index: 3 , Last index: 3 , Adjusting? true First index: 3 , Last index: 3 , Adjusting? false Selections: 3/D First index: 3 , Last index: 4 , Adjusting? true First index: 3 , Last index: 4 , Adjusting? false Selections: 4/E First index: 4 , Last index: 7 , Adjusting? true First index: 4 , Last index: 7 , Adjusting? false Selections: 7/H |