Table of Contents
1 JList
与ComboBox不同的是JList把所有的可选项都可见,而ComboBox把所有Item隐藏等待用户下拉后才看见。
原型是JList<E>,是个容器,2 构造函数
JList()Constructs a JList with an empty, read-only, model.JList(E[] listData)Constructs a JList that displays the elements in the specified array.JList(ListModeldataModel)Constructs a JList that displays elements from the specified, non-null, model.JList(Vector listData)Constructs a JList that displays the elements in the specified Vector.
3 ListMode
This interface defines the methods components like JList use to get the value of each cell in a list and the length of the list. Logically the model is a vector, indices vary from 0 to ListDataModel.getSize() - 1.
3.1 DefaultListMode
3.1.1 addElement(E element)
添加元素
3.1.2 add(int index, E element)
在指定位置插入指定元素。
4 JList 几个函数
4.1 getSelectedValues()
获取所选元素的值
4.2 getSelectedIndices()
获取所选元素的索引
5 addListSelectionListener(ListSelectionListener)
5.1 ListSelectionListener
有Item选中时发生事件
5.2 valueChanged(ListSelectionEvent e)
6 程序示例
package xjtu.vf.swing;import java.awt.Color;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.BorderFactory;import javax.swing.DefaultListModel;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JList;import javax.swing.JTextArea;import javax.swing.border.Border;import javax.swing.event.ListSelectionEvent;import javax.swing.event.ListSelectionListener;public class List extends JFrame { private String[] flavors = { "A", "B", "C", "D", "E", "F" }; private DefaultListModel lItems = new DefaultListModel(); private JList lst = new JList(lItems); private JTextArea t = new JTextArea(flavors.length, 20); private JButton b = new JButton("Add Item"); private ActionListener bl = new ActionListener() { public void actionPerformed(ActionEvent e) { if (count < flavors.length) lItems.add(0, flavors[count++]); else b.setEnabled(false); } }; private ListSelectionListener lsl = new ListSelectionListener() { @SuppressWarnings("deprecation") public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; t.setText(""); for (Object item : lst.getSelectedValues()) t.append(item + "\n"); } }; private int count = 0; public List() { t.setEditable(true); setLayout(new FlowLayout()); Border brd = BorderFactory.createMatteBorder(1, 1, 2, 2, Color.black); lst.setBorder(brd); t.setBorder(brd); for (int i = 0; i < 4; i++) lItems.addElement(flavors[count++]); add(t); add(lst); add(b); b.addActionListener(bl); lst.addListSelectionListener(lsl); } public static void main(String[] args) { SwingConsole.run(new List(), 250, 375); }}
Date: 2011-11-20 23:49:33
HTML generated by org-mode 6.33x in emacs 23