Java Tutorial/Swing/JList Selection

Материал из Java эксперт
Версия от 15:32, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Add another selection - the third item

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    int start = 2;
    int end = 2;
    list.addSelectionInterval(start, end); 
  }
}





A single-selection JList.

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Main {
  String languages[] = { "Java", "Perl", "Python", "C++", "Basic", "C#" };
  JList jlst = new JList(languages);
  Main() {
    JFrame jfrm = new JFrame("Use JList");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(200, 160);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jlst.addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent le) {
        int idx = jlst.getSelectedIndex();
        if (idx != -1)
          System.out.println("Current selection: " + languages[idx]);
        else
          System.out.println("Please choose a language.");
      }
    });
    jfrm.add(new JScrollPane(jlst));
    jfrm.setSize(300, 300);
    jfrm.setVisible(true);
  }
  public static void main(String args[]) {
    new Main();
  }
}





Clear all selections

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    list.clearSelection();
  }
}





Deselect the first item

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    int start = 0;
    int end = 0;
    list.removeSelectionInterval(start, end);
  }
}





Determine if there are any selected items

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    boolean anySelected = !list.isSelectionEmpty();
  }
}





Get the index of the last selected item

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    int lastSelIx = list.getMaxSelectionIndex();
  }
}





Getting the Selected Items in a JList Component

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    // Get the index of all the selected items
    int[] selectedIx = list.getSelectedIndices();
    // Get all the selected items using the indices
    for (int i = 0; i < selectedIx.length; i++) {
      Object sel = list.getModel().getElementAt(selectedIx[i]);
    }
    // Get the index of the first selected item
    int firstSelIx = list.getSelectedIndex();
  }
}





Listening for Changes to the Items in a JList Component

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
public class Main {
  public static void main(String[] argv) throws Exception {
    JList list = new JList();
    // Register a list data listener
    DefaultListModel model = (DefaultListModel) list.getModel();
    model.addListDataListener(new MyListDataListener());
  }
}
class MyListDataListener implements ListDataListener {
  public void intervalAdded(ListDataEvent evt) {
    DefaultListModel model = (DefaultListModel) evt.getSource();
    int start = evt.getIndex0();
    int end = evt.getIndex1();
    int count = end - start + 1;
    for (int i = start; i <= end; i++) {
      Object item = model.getElementAt(i);
    }
  }
  public void intervalRemoved(ListDataEvent evt) {
    int start = evt.getIndex0();
    int end = evt.getIndex1();
    int count = end - start + 1;
  }
  public void contentsChanged(ListDataEvent evt) {
    DefaultListModel model = (DefaultListModel) evt.getSource();
    int start = evt.getIndex0();
    int end = evt.getIndex1();
    int count = end - start + 1;
    for (int i = start; i <= end; i++) {
      Object item = model.getElementAt(i);
    }
  }
}





Listening for Changes to the Selection in a JList Component

import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    list.addListSelectionListener(new MyListSelectionListener());
  }
}
class MyListSelectionListener implements ListSelectionListener {
  public void valueChanged(ListSelectionEvent evt) {
    if (!evt.getValueIsAdjusting()) {
      JList list = (JList) evt.getSource();
      Object[] selected = list.getSelectedValues();
      for (int i = 0; i < selected.length; i++) {
        Object sel = selected[i];
      }
    }
  }
}





List selection event

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





Multiple ranges of selected items are allowed

import javax.swing.DefaultListSelectionModel;
import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    list.setSelectionMode(DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
  }
}





Select all the items

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    int start = 0;
    int end = list.getModel().getSize() - 1;
    if (end >= 0) {
      list.setSelectionInterval(start, end);
    }
  }
}





Select the first item

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    int start = 0;
    int end = 0;
    list.setSelectionInterval(start, end);
  }
}





Setting the Selected Items in a JList Component

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    // Select the second item
    int start = 1;
    int end = 1;
    list.setSelectionInterval(start, end);
  }
}





Setting the Selection Mode of a JList Component

import javax.swing.DefaultListSelectionModel;
import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    // Get the current selection model mode
    int mode = list.getSelectionMode(); // MULTIPLE_INTERVAL_SELECTION
    // Only one item can be selected
    list.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
  }
}





The selected items must be in a contiguous range

import javax.swing.DefaultListSelectionModel;
import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    list.setSelectionMode(DefaultListSelectionModel.SINGLE_INTERVAL_SELECTION);
  }
}