Swing开发之JList篇

 
由JList类代表的Swing列表显示一个可选取对象列表,它支持三种选取模式:单选取、单间隔选取和多间隔选取。
  JList类把维护和绘制列表的工作委托给一个对象来完成。一个列表的模型维护一个对象列表,列表单元绘制器将这些对象绘制在列表单元中。
  缺省情况下,列表单元绘制器是DefaultListCellRenderrer的实例,它绘制表17-1中列出的对象。图标和字符串按原样显示,而所有其他类型对象的绘制方式是:通过显示从这些对象的toString返回的字符串来绘制这些对象。

构造方法
JList()
          构造一个使用空模型的 JList。
JList(ListModel dataModel)
          构造一个 JList,使其使用指定的非 null 模型显示元素。
JList(Object[] listData)
          构造一个 JList,使其显示指定数组中的元素。
JList(Vector<?> listData)
          构造一个 JList,使其显示指定 Vector 中的元素。

常用方法
addListSelectionListener(ListSelectionListener listener)
          为每次选择发生更改时要通知的列表添加侦听器。
addSelectionInterval(int anchor, int lead)
          将选择设置为指定间隔与当前选择的并集。
createSelectionModel()
          返回 DefaultListSelectionModel 实例。
getCellRenderer()
          返回呈现列表项的对象。
getModel()
          返回保存由 JList 组件显示的项列表的数据模型。
getSelectedIndex()
          返回所选的第一个索引;如果没有选择项,则返回 -1。
getSelectedValue()
          返回所选的第一个值,如果选择为空,则返回 null。
getSelectionModel()
          返回当前选择模型的值。
isSelectionEmpty()
          如果什么也没有选择,则返回 true。
setListData(Object[] listData)
          根据一个 object 数组构造 ListModel,然后对其应用 setModel。
setListData(Vector<?> listData)
          根据 Vector 构造 ListModel,然后对其应用 setModel。
setModel(ListModel model)
          设置表示列表内容或“值”的模型,并在通知 PropertyChangeListener 之后清除列表选择。
setSelectedIndex(int index)
          选择单个单元。
setSelectionMode(int selectionMode)
          确定允许单项选择还是多项选择。
setSelectionModel(ListSelectionModel selectionModel)
          将列表的 selectionModel 设置为非 null 的 ListSelectionModel 实现。

例 1:采用数组对象创建JList并设置JList背景颜色和边框
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.border.Border;

public class JListBackground extends JPanel {
  private static final Color lightBlue = new Color(153, 204, 255);

  public JListBackground() {
    super();
    setBackground(lightBlue);
  }

  public static void addComponentsToPane(Container pane) {
    String[] bruteForceCode = { "int count = 0",
        "int m = mPattern.length();",
        "int n = mSource .length();",
        "outer:",
        " ++count;",
        " }",
        " return count;",
        "}"
    };
    JList list = new JList(bruteForceCode);
    Border etch = BorderFactory.createEtchedBorder();
    list.setBorder(BorderFactory.createTitledBorder(etch, "Brute Force Code"));
    JPanel listPanel = new JPanel();
    listPanel.add(list);
    listPanel.setBackground(lightBlue);
    list.setBackground(lightBlue);

    pane.add(listPanel, BorderLayout.CENTER);
    pane.setBackground(lightBlue);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame("Brute Force Algorithm");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addComponentsToPane(frame.getContentPane());
    frame.pack();
    frame.setSize(800, 600);
    frame.setVisible(true);
  }
}


例 2:采用Vector对象创建JList对象
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

public class StoringvalueinVectorandaddingthemintoJList {

  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Vector months = new Vector();
    JList list = new JList(months);

//用Vector对象创建JList,可以在创建后增加内容,而采用数组创建则不可以
    months.addElement("January");
    months.addElement("December");

    frame.add(new JScrollPane(list));

    frame.setSize(300, 200);
    frame.setVisible(true);
  }

}

例 3:改变JList中值
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

public class ModifyModelSampleModelAction {
  static String labels[] = { "A", "B", "C", "D", "E", "F", "G" };

  public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Fill model
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
      model.addElement(labels[i]);
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);

    JButton jb = new JButton("add F");

    jb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        model.add(0, "First");
        model.clear();
        model.addElement("Last");
        model.addElement("Last");
        model.addElement("Last");
        model.addElement("Last");
       
        int size = model.getSize();
        model.insertElementAt("Middle", size / 2);
        model.set(0, "New First");
        model.setElementAt("New Last", size - 1);

        model.remove(0);
        // model.removeAllElements();
    //    model.removeElement("Last");
  //      model.removeElementAt(size / 2);
//        model.removeRange(0, size / 2);
      }
    });

    frame.add(jb, BorderLayout.SOUTH);

    frame.setSize(640, 300);
    frame.setVisible(true);
  }
}

例 4:向JList增加监听时间
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

public class ModifyModelSampleListDataListener {
  static String labels[] = { "A", "B", "C", "D", "E", "F", "G" };

  public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Fill model
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
      model.addElement(labels[i]);
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);

   
    ListDataListener listDataListener = new ListDataListener() {
      public void contentsChanged(ListDataEvent listDataEvent) {
        appendEvent(listDataEvent);
      }

      public void intervalAdded(ListDataEvent listDataEvent) {
        appendEvent(listDataEvent);
      }

      public void intervalRemoved(ListDataEvent listDataEvent) {
        appendEvent(listDataEvent);
      }

      private void appendEvent(ListDataEvent listDataEvent) {
        switch (listDataEvent.getType()) {
        case ListDataEvent.CONTENTS_CHANGED:
          System.out.println("Type: Contents Changed");
          break;
        case ListDataEvent.INTERVAL_ADDED:
          System.out.println("Type: Interval Added");
          break;
        case ListDataEvent.INTERVAL_REMOVED:
          System.out.println("Type: Interval Removed");
          break;
        }
        DefaultListModel theModel = (DefaultListModel) listDataEvent.getSource();
        System.out.println(theModel);
      }
    };

    model.addListDataListener(listDataListener);
   
    JButton jb = new JButton("add F");

    jb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        model.add(0, "First");
      }
    });
   
    frame.add(jb,BorderLayout.SOUTH);   
   
    frame.setSize(640, 300);
    frame.setVisible(true);
  }
}

例 5:向JList中增加双击事件
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

public class JListLocationToIndexSample {
  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);

    MouseListener mouseListener = new MouseAdapter() {
      public void mouseClicked(MouseEvent mouseEvent) {
        JList theList = (JList) mouseEvent.getSource();
        if (mouseEvent.getClickCount() == 2) {
          int index = theList.locationToIndex(mouseEvent.getPoint());
          if (index >= 0) {
            Object o = theList.getModel().getElementAt(index);
            System.out.println("Double-clicked on: " + o.toString());
          }
        }
      }
    };
    jlist.addMouseListener(mouseListener);

    frame.setSize(350, 200);
    frame.setVisible(true);
  }
}

例 6:在JList中增加复选框和图片
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;

import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.metal.MetalIconFactory;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellRenderer;


public class CheckListExample extends JFrame {

  public CheckListExample() {
    super("CheckList Example");
    String[] strs = { "swing", "home", "basic", "metal", "JList" };

    final JList list = new JList(createData(strs));

    // set "home" icon
    Icon icon = MetalIconFactory.getFileChooserHomeFolderIcon();
    ((CheckableItem) list.getModel().getElementAt(1)).setIcon(icon);

    list.setCellRenderer(new CheckListRenderer());
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setBorder(new EmptyBorder(0, 4, 0, 0));
    list.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        int index = list.locationToIndex(e.getPoint());
        CheckableItem item = (CheckableItem) list.getModel()
            .getElementAt(index);
        item.setSelected(!item.isSelected());
        Rectangle rect = list.getCellBounds(index, index);
        list.repaint(rect);
      }
    });
    JScrollPane sp = new JScrollPane(list);

    final JTextArea textArea = new JTextArea(3, 10);
    JScrollPane textPanel = new JScrollPane(textArea);
    JButton printButton = new JButton("print");
    printButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        ListModel model = list.getModel();
        int n = model.getSize();
        for (int i = 0; i < n; i++) {
          CheckableItem item = (CheckableItem) model.getElementAt(i);
          if (item.isSelected()) {
            textArea.append(item.toString());
            textArea.append(System.getProperty("line.separator"));
          }
        }
      }
    });
    JButton clearButton = new JButton("clear");
    clearButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        textArea.setText("");
      }
    });
    JPanel panel = new JPanel(new GridLayout(2, 1));
    panel.add(printButton);
    panel.add(clearButton);

    getContentPane().add(sp, BorderLayout.CENTER);
    getContentPane().add(panel, BorderLayout.EAST);
    getContentPane().add(textPanel, BorderLayout.SOUTH);
  }

  private CheckableItem[] createData(String[] strs) {
    int n = strs.length;
    CheckableItem[] items = new CheckableItem[n];
    for (int i = 0; i < n; i++) {
      items[i] = new CheckableItem(strs[i]);
    }
    return items;
  }

  class CheckableItem {
    private String str;

    private boolean isSelected;

    private Icon icon;

    public CheckableItem(String str) {
      this.str = str;
      isSelected = false;
    }

    public void setSelected(boolean b) {
      isSelected = b;
    }

    public boolean isSelected() {
      return isSelected;
    }

    public String toString() {
      return str;
    }

    public void setIcon(Icon icon) {
      this.icon = icon;
    }

    public Icon getIcon() {
      return icon;
    }
  }

  class CheckListRenderer extends CheckRenderer implements ListCellRenderer {
    Icon commonIcon;

    public CheckListRenderer() {
      check.setBackground(UIManager.getColor("List.textBackground"));
      label.setForeground(UIManager.getColor("List.textForeground"));
      commonIcon = UIManager.getIcon("Tree.leafIcon");
    }

    public Component getListCellRendererComponent(JList list, Object value,
        int index, boolean isSelected, boolean hasFocus) {
      setEnabled(list.isEnabled());
      check.setSelected(((CheckableItem) value).isSelected());
      label.setFont(list.getFont());
      label.setText(value.toString());
      label.setSelected(isSelected);
      label.setFocus(hasFocus);
      Icon icon = ((CheckableItem) value).getIcon();
      if (icon == null) {
        icon = commonIcon;
      }
      label.setIcon(icon);
      return this;
    }
  }

  public static void main(String args[]) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}

    CheckListExample frame = new CheckListExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

class CheckRenderer extends JPanel implements TreeCellRenderer {
  protected JCheckBox check;

  protected TreeLabel label;

  public CheckRenderer() {
    setLayout(null);
    add(check = new JCheckBox());
    add(label = new TreeLabel());
    check.setBackground(UIManager.getColor("Tree.textBackground"));
    label.setForeground(UIManager.getColor("Tree.textForeground"));
  }

  public Component getTreeCellRendererComponent(JTree tree, Object value,
      boolean isSelected, boolean expanded, boolean leaf, int row,
      boolean hasFocus) {
    String stringValue = tree.convertValueToText(value, isSelected,
        expanded, leaf, row, hasFocus);
    setEnabled(tree.isEnabled());
    check.setSelected(((CheckNode) value).isSelected());
    label.setFont(tree.getFont());
    label.setText(stringValue);
    label.setSelected(isSelected);
    label.setFocus(hasFocus);
    if (leaf) {
      label.setIcon(UIManager.getIcon("Tree.leafIcon"));
    } else if (expanded) {
      label.setIcon(UIManager.getIcon("Tree.openIcon"));
    } else {
      label.setIcon(UIManager.getIcon("Tree.closedIcon"));
    }
    return this;
  }

  public Dimension getPreferredSize() {
    Dimension d_check = check.getPreferredSize();
    Dimension d_label = label.getPreferredSize();
    return new Dimension(d_check.width + d_label.width,
        (d_check.height < d_label.height ? d_label.height
            : d_check.height));
  }

  public void doLayout() {
    Dimension d_check = check.getPreferredSize();
    Dimension d_label = label.getPreferredSize();
    int y_check = 0;
    int y_label = 0;
    if (d_check.height < d_label.height) {
      y_check = (d_label.height - d_check.height) / 2;
    } else {
      y_label = (d_check.height - d_label.height) / 2;
    }
    check.setLocation(0, y_check);
    check.setBounds(0, y_check, d_check.width, d_check.height);
    label.setLocation(d_check.width, y_label);
    label.setBounds(d_check.width, y_label, d_label.width, d_label.height);
  }

  public void setBackground(Color color) {
    if (color instanceof ColorUIResource)
      color = null;
    super.setBackground(color);
  }

  public class TreeLabel extends JLabel {
    boolean isSelected;

    boolean hasFocus;

    public TreeLabel() {
    }

    public void setBackground(Color color) {
      if (color instanceof ColorUIResource)
        color = null;
      super.setBackground(color);
    }

    public void paint(Graphics g) {
      String str;
      if ((str = getText()) != null) {
        if (0 < str.length()) {
          if (isSelected) {
            g.setColor(UIManager
                .getColor("Tree.selectionBackground"));
          } else {
            g.setColor(UIManager.getColor("Tree.textBackground"));
          }
          Dimension d = getPreferredSize();
          int imageOffset = 0;
          Icon currentI = getIcon();
          if (currentI != null) {
            imageOffset = currentI.getIconWidth()
                + Math.max(0, getIconTextGap() - 1);
          }
          g.fillRect(imageOffset, 0, d.width - 1 - imageOffset,
              d.height);
          if (hasFocus) {
            g.setColor(UIManager
                .getColor("Tree.selectionBorderColor"));
            g.drawRect(imageOffset, 0, d.width - 1 - imageOffset,
                d.height - 1);
          }
        }
      }
      super.paint(g);
    }

    public Dimension getPreferredSize() {
      Dimension retDimension = super.getPreferredSize();
      if (retDimension != null) {
        retDimension = new Dimension(retDimension.width + 3,
            retDimension.height);
      }
      return retDimension;
    }

    public void setSelected(boolean isSelected) {
      this.isSelected = isSelected;
    }

    public void setFocus(boolean hasFocus) {
      this.hasFocus = hasFocus;
    }
  }
}

class CheckNode extends DefaultMutableTreeNode {

  public final static int SINGLE_SELECTION = 0;

  public final static int DIG_IN_SELECTION = 4;

  protected int selectionMode;

  protected boolean isSelected;

  public CheckNode() {
    this(null);
  }

  public CheckNode(Object userObject) {
    this(userObject, true, false);
  }

  public CheckNode(Object userObject, boolean allowsChildren,
      boolean isSelected) {
    super(userObject, allowsChildren);
    this.isSelected = isSelected;
    setSelectionMode(DIG_IN_SELECTION);
  }

  public void setSelectionMode(int mode) {
    selectionMode = mode;
  }

  public int getSelectionMode() {
    return selectionMode;
  }

  public void setSelected(boolean isSelected) {
    this.isSelected = isSelected;

    if ((selectionMode == DIG_IN_SELECTION) && (children != null)) {
      Enumeration e = children.elements();
      while (e.hasMoreElements()) {
        CheckNode node = (CheckNode) e.nextElement();
        node.setSelected(isSelected);
      }
    }
  }

  public boolean isSelected() {
    return isSelected;
  }
}

例 7:可编辑JList
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;

public class EditableListExample extends JFrame {

  public EditableListExample() {
    super("Editable List Example");

    String[] data = { "a", "b", "c", "d", "e", "f", "g" };

    JList list = new JList(data);
    JScrollPane scrollList = new JScrollPane(list);
    scrollList.setMinimumSize(new Dimension(100, 80));
    Box listBox = new Box(BoxLayout.Y_AXIS);
    listBox.add(scrollList);
    listBox.add(new JLabel("JList"));

    DefaultTableModel dm = new DefaultTableModel();
    Vector dummyHeader = new Vector();
    dummyHeader.addElement("");
    dm.setDataVector(strArray2Vector(data), dummyHeader);
    JTable table = new JTable(dm);
    table.setShowGrid(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scrollTable = new JScrollPane(table);
    scrollTable.setColumnHeader(null);
    scrollTable.setMinimumSize(new Dimension(100, 80));
    Box tableBox = new Box(BoxLayout.Y_AXIS);
    tableBox.add(scrollTable);
    tableBox.add(new JLabel("JTable"));

    Container c = getContentPane();
    c.setLayout(new BoxLayout(c, BoxLayout.X_AXIS));
    c.add(listBox);
    c.add(new JSeparator(SwingConstants.VERTICAL));
    //c.add(new JLabel("test"));
    //c.add(new JSeparator(SwingConstants.HORIZONTAL));
    c.add(tableBox);
    setSize(220, 130);
    setVisible(true);
  }

  private Vector strArray2Vector(String[] str) {
    Vector vector = new Vector();
    for (int i = 0; i < str.length; i++) {
      Vector v = new Vector();
      v.addElement(str[i]);
      vector.addElement(v);
    }
    return vector;
  }

  public static void main(String[] args) {
    final EditableListExample frame = new EditableListExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值