Implement a graphical list selection monitor : ListSelectionListener « Swing Event « Java Tutorial






import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class SelectionMonitor extends JPanel {

  String label[] = { "1", "2", "3"};

  JCheckBox checks[] = new JCheckBox[label.length];

  JList list = new JList(label);

  public SelectionMonitor() {
    JScrollPane pane = new JScrollPane(list);
    add(pane);
    list.addListSelectionListener(new RadioUpdater());

    for (int i = 0; i < label.length; i++) {
      checks[i] = new JCheckBox("Selection " + i);
      add(checks[i]);
    }
  }

  public static void main(String s[]) {

    JFrame frame = new JFrame("Selection Monitor");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new SelectionMonitor());
    frame.pack();
    frame.setVisible(true);

  }
}
class RadioUpdater implements ListSelectionListener {
  public void valueChanged(ListSelectionEvent e) {
    if ((!e.getValueIsAdjusting()) || (e.getFirstIndex() == -1))
      return;

    for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) {
      System.out.println(((JList) e.getSource()).isSelectedIndex(i));
    }
  }
}








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