List selection event : JList Selection « Swing « Java Tutorial






import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class SelectionHandler implements ActionListener, ListSelectionListener {
  private JLabel direction;

  private JList source, destination;

  public SelectionHandler(JLabel d, JList left, JList right) {
    direction = d;
    source = left;
    destination = right;
  }

  public void actionPerformed(ActionEvent a) {
    JComboBox cb = (JComboBox) a.getSource();
    String selected = (String) cb.getSelectedItem();
    String current = direction.getText();
    if (!selected.equals(current)) {
      direction.setText(selected);
      JList temp = source;
      source = destination;
      destination = temp;
      source.clearSelection();
      destination.clearSelection();
    }

  }

  public void valueChanged(ListSelectionEvent e) {
    JList list = (JList) e.getSource();
    String item = (String) source.getSelectedValue();
    System.out.println(item);
    if (item != null && !item.equals("")) {
      removeFromSource(item);
      addToDestination(item);
    }
  }

  private void removeFromSource(String item) {
    ListModel model = source.getModel();
    Vector listData = new Vector();
    for (int i = 0; i < model.getSize(); i++) {
      listData.addElement(model.getElementAt(i));
    }
    listData.removeElement(item);
    source.setListData(listData);
  }

  private void addToDestination(String item) {
    ListModel model = destination.getModel();
    Vector listData = new Vector();
    for (int i = 0; i < model.getSize(); i++) {
      listData.addElement(model.getElementAt(i));
    }
    listData.addElement(item);
    destination.setListData(listData);
  }
}








14.43.JList Selection
14.43.1.List selection event
14.43.2.A single-selection JList.
14.43.3.Listening for Changes to the Items in a JList Component
14.43.4.Listening for Changes to the Selection in a JList Component
14.43.5.Setting the Selection Mode of a JList Component
14.43.6.The selected items must be in a contiguous range
14.43.7.Multiple ranges of selected items are allowed
14.43.8.Setting the Selected Items in a JList Component
14.43.9.Select all the items
14.43.10.Clear all selections
14.43.11.Select the first item
14.43.12.Add another selection - the third item
14.43.13.Deselect the first item
14.43.14.Getting the Selected Items in a JList Component
14.43.15.Get the index of the last selected item
14.43.16.Determine if there are any selected items