首页 > 代码库 > Swing开发之JComboBox篇

Swing开发之JComboBox篇

JList和ComboBox很相似,因为这两个组件都显示一个项列表。因此,它们都有扩展ListModel接口的模型。而且,这两个组件都有绘制器,这些绘制器通过实现ListCellBenderer接口来绘制列表单元。
  但是,列表和组合框在施工方面还是有差别的。列表单是不可编辑的,但是组合框可以配备一个编辑器。JComboBox组件把编辑工作交给实现ComboBoxEdit接口的一个对象来处理。
  列表支持三个选取模式,并把选取工作实现ListSelectionModel接口的一个对象来处理。组合框在一个时刻只有一个可选取的项,而且选取工作由组合框模型来处理。另一方面,组合框支持键选取,即在某项上按下一下键就可以选取这个项,但列表不能这样做。

构造函数
JComboBox()
          创建具有默认数据模型的 JComboBox。
JComboBox(ComboBoxModel aModel)
          创建一个 JComboBox,其项取自现有的 ComboBoxModel 中。
JComboBox(Object[] items)
          创建包含指定数组中的元素的 JComboBox。
JComboBox(Vector<?> items)
          创建包含指定 Vector 中的元素的 JComboBox。

常用方法
addActionListener(ActionListener l)
          添加 ActionListener。
addItem(Object anObject)
          为项列表添加项。
addItemListener(ItemListener aListener)
          添加 ItemListener。
configureEditor(ComboBoxEditor anEditor, Object anItem)
          利用指定项初始化编辑器。
getEditor()
          返回用于绘制和编辑 JComboBox 字段中所选项的编辑器。
getItemAt(int index)
          返回指定索引处的列表项。
getItemCount()
          返回列表中的项数。
getModel()
          返回 JComboBox 当前使用的数据模型。
getRenderer()
          返回用于显示 JComboBox 字段中所选项的渲染器。
getSelectedIndex()
          返回列表中与给定项匹配的第一个选项。
getSelectedItem()
          返回当前所选项。
insertItemAt(Object anObject, int index)
          在项列表中的给定索引处插入项。
isEditable()
          如果 JComboBox 可编辑,则返回 true。
removeAllItems()
          从项列表中移除所有项。
removeItem(Object anObject)
          从项列表中移除项。
removeItemAt(int anIndex)
          移除 anIndex 处的项。
setModel(ComboBoxModel aModel)
          设置 JComboBox 用于获取项列表的数据模型。
setRenderer(ListCellRenderer aRenderer)
          设置渲染器,该渲染器用于绘制列表项和从 JComboBox 字段的列表中选择的项。
setSelectedIndex(int anIndex)
          选择索引 anIndex 处的项。
setSelectedItem(Object anObject)
          将组合框显示区域中所选项设置为参数中的对象。

 

例 1:给JComboBox增加ItemListener和ActionListener

import java.awt.BorderLayout;import java.awt.ItemSelectable;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import javax.swing.JComboBox;import javax.swing.JFrame;public class ItemListenerSelectingComboSample {  static private String selectedString(ItemSelectable is) {    Object selected[] = is.getSelectedObjects();    return ((selected.length == 0) ? "null" : (String) selected[0]);  }  public static void main(String args[]) {    String labels[] = { "A", "B", "C", "D", "E", "F" };    JFrame frame = new JFrame("Selecting JComboBox");    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    JComboBox comboBox = new JComboBox(labels);    comboBox.setEditable(true);    comboBox.addActionListener(new ActionListener() {      public void actionPerformed(ActionEvent e) {        System.out.println("Selected index=" + ((JComboBox)e.getSource()).getItemCount());      }    });    frame.add(comboBox, BorderLayout.SOUTH);    ItemListener itemListener = new ItemListener() {      public void itemStateChanged(ItemEvent itemEvent) {        int state = itemEvent.getStateChange();        System.out.println((state == ItemEvent.SELECTED) ? "Selected" : "Deselected");        System.out.println("Item: " + itemEvent.getItem());        ItemSelectable is = itemEvent.getItemSelectable();        System.out.println(", Selected: " + selectedString(is));      }    };    comboBox.addItemListener(itemListener);    frame.setSize(400, 200);    frame.setVisible(true);  }}

  

例 2:采用模板创建JComboBox,同一个模板创建的两个不同JComboBox,对模板操作时两个JComboBox会同时改变

import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.DefaultComboBoxModel;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JPanel;public class SharedDataBetweenComboBoxSample {  public static void main(String args[]) {    final String labels[] = { "A", "B", "C", "D", "E", "F", "G" };    final DefaultComboBoxModel model = new DefaultComboBoxModel(labels);    JFrame frame = new JFrame("Shared Data");    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    JPanel panel = new JPanel();    JComboBox comboBox1 = new JComboBox(model);    comboBox1.setEditable(true);    JComboBox comboBox2 = new JComboBox(model);    comboBox2.setEditable(true);    panel.add(comboBox1);    panel.add(comboBox2);    frame.add(panel, BorderLayout.NORTH);    JButton button = new JButton("Add");    frame.add(button, BorderLayout.SOUTH);    ActionListener actionListener = new ActionListener() {      public void actionPerformed(ActionEvent actionEvent) {        model.addElement("New Added");      }    };    button.addActionListener(actionListener);    frame.setSize(300, 200);    frame.setVisible(true);  }}//JComboBox与JList共用一个模板import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.DefaultComboBoxModel;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JList;import javax.swing.JPanel;import javax.swing.JScrollPane;public class SharedDataBetweenComboBoxAndListSample {  public static void main(String args[]) {    final String labels[] = { "A", "B", "C", "D", "E", "F", "G" };    final DefaultComboBoxModel model = new DefaultComboBoxModel(labels);    JFrame frame = new JFrame("Shared Data");    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    JPanel panel = new JPanel();    JComboBox comboBox1 = new JComboBox(model);    comboBox1.setEditable(true);    panel.add(comboBox1);    frame.add(panel, BorderLayout.NORTH);    JList jlist = new JList(model);    JScrollPane scrollPane = new JScrollPane(jlist);    frame.add(scrollPane, BorderLayout.CENTER);    JButton button = new JButton("Add");    frame.add(button, BorderLayout.SOUTH);    ActionListener actionListener = new ActionListener() {      public void actionPerformed(ActionEvent actionEvent) {        model.addElement("New Added");      }    };    button.addActionListener(actionListener);    frame.setSize(300, 200);    frame.setVisible(true);  }}

  例 3:采用ArrayList组装JComboBox

import java.awt.BorderLayout;import java.util.ArrayList;import java.util.Collection;import javax.swing.AbstractListModel;import javax.swing.ComboBoxModel;import javax.swing.JComboBox;import javax.swing.JFrame;class ArrayListComboBoxModel extends AbstractListModel implements ComboBoxModel {  private Object selectedItem;  private ArrayList anArrayList;  public ArrayListComboBoxModel(ArrayList arrayList) {    anArrayList = arrayList;  }  public Object getSelectedItem() {    return selectedItem;  }  public void setSelectedItem(Object newValue) {    selectedItem = newValue;  }  public int getSize() {    return anArrayList.size();  }  public Object getElementAt(int i) {    return anArrayList.get(i);  }}public class ArrayListComboBoxModelDemo {  public static void main(String args[]) {    JFrame frame = new JFrame("ArrayListComboBoxModel");    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    ArrayList<Object> arrayList = new ArrayList<Object>();    arrayList.add("A");    arrayList.add("B");    arrayList.add("C");    ArrayListComboBoxModel model = new ArrayListComboBoxModel(arrayList);    arrayList.add("A");    arrayList.add("B");    arrayList.add("C");    JComboBox comboBox = new JComboBox(model);    frame.add(comboBox, BorderLayout.NORTH);    frame.setSize(300, 225);    frame.setVisible(true);  }}

  例 4:给JComboBox每项增加图片

import java.awt.BorderLayout;import java.awt.Color;import java.awt.Component;import java.awt.Font;import java.awt.Graphics;import javax.swing.DefaultListCellRenderer;import javax.swing.Icon;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JList;import javax.swing.ListCellRenderer;class ComplexCellRenderer implements ListCellRenderer {  protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();  public Component getListCellRendererComponent(JList list, Object value, int index,      boolean isSelected, boolean cellHasFocus) {    Font theFont = null;    Color theForeground = null;    Icon theIcon = null;    String theText = null;    JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,        isSelected, cellHasFocus);    if (value instanceof Object[]) {      Object values[] = (Object[]) value;      theFont = (Font) values[0];      theForeground = (Color) values[1];      theIcon = (Icon) values[2];      theText = (String) values[3];    } else {      theFont = list.getFont();      theForeground = list.getForeground();      theText = "";    }    if (!isSelected) {      renderer.setForeground(theForeground);    }    if (theIcon != null) {      renderer.setIcon(theIcon);    }    renderer.setText(theText);    renderer.setFont(theFont);    return renderer;  }}public class ComplexRenderingSample {  public static void main(String args[]) {    Object elements[][] = {        { new Font("Helvetica", Font.PLAIN, 20), Color.RED, new MyIcon(), "A" },        { new Font("TimesRoman", Font.BOLD, 14), Color.BLUE, new MyIcon(), "A" },        { new Font("Courier", Font.ITALIC, 18), Color.GREEN, new MyIcon(), "A" },        { new Font("Helvetica", Font.BOLD | Font.ITALIC, 12), Color.GRAY, new MyIcon(), "A" },        { new Font("TimesRoman", Font.PLAIN, 32), Color.PINK, new MyIcon(), "A" },        { new Font("Courier", Font.BOLD, 16), Color.YELLOW, new MyIcon(), "A" },        { new Font("Helvetica", Font.ITALIC,Swing开发之JComboBox篇, Color.DARK_GRAY, new MyIcon(), "A" } };    JFrame frame = new JFrame("Complex Renderer");    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    ListCellRenderer renderer = new ComplexCellRenderer();    JComboBox comboBox = new JComboBox(elements);    comboBox.setRenderer(renderer);    frame.add(comboBox, BorderLayout.NORTH);       frame.setSize(300, 200);    frame.setVisible(true);  }}class MyIcon implements Icon {  public MyIcon() {  }  public int getIconHeight() {    return 20;  }  public int getIconWidth() {    return 20;  }  public void paintIcon(Component c, Graphics g, int x, int y) {    g.setColor(Color.RED);    g.drawRect(0, 0, 25, 25);  }}

  例 5:改变JComboBox编辑框颜色

import java.awt.BorderLayout;import java.awt.Color;import java.awt.Component;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.ComboBoxEditor;import javax.swing.JButton;import javax.swing.JColorChooser;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.event.EventListenerList;class ColorComboBoxEditor implements ComboBoxEditor {  final protected JButton editor;  protected EventListenerList listenerList = new EventListenerList();  public ColorComboBoxEditor(Color initialColor) {    editor = new JButton("");    editor.setBackground(initialColor);    ActionListener actionListener = new ActionListener() {      public void actionPerformed(ActionEvent e) {        Color currentBackground = editor.getBackground();        Color color = JColorChooser.showDialog(editor, "Color Chooser", currentBackground);        if ((color != null) && (currentBackground != color)) {          editor.setBackground(color);          fireActionEvent(color);        }      }    };    editor.addActionListener(actionListener);  }  public void addActionListener(ActionListener l) {    listenerList.add(ActionListener.class, l);  }  public Component getEditorComponent() {    return editor;  }  public Object getItem() {    return editor.getBackground();  }  public void removeActionListener(ActionListener l) {    listenerList.remove(ActionListener.class, l);  }  public void selectAll() {    // Ignore  }  public void setItem(Object newValue) {    if (newValue instanceof Color) {      Color color = (Color) newValue;      editor.setBackground(color);    } else {      try {        Color color = Color.decode(newValue.toString());        editor.setBackground(color);      } catch (NumberFormatException e) {      }    }  }  protected void fireActionEvent(Color color) {    Object listeners[] = listenerList.getListenerList();    for (int i = listeners.length - 2; i >= 0; i -= 2) {      if (listeners[i] == ActionListener.class) {        ActionEvent actionEvent = new ActionEvent(editor, ActionEvent.ACTION_PERFORMED, color            .toString());        ((ActionListener) listeners[i + 1]).actionPerformed(actionEvent);      }    }  }}public class ColorComboBoxEditorDemo {  public static void main(String args[]) {    Color colors[] = { Color.RED, Color.BLUE, Color.BLACK, Color.WHITE };    JFrame frame = new JFrame("Editable JComboBox");    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    final JComboBox comboBox = new JComboBox(colors);    comboBox.setEditable(true);    comboBox.setEditor(new ColorComboBoxEditor(Color.RED));    frame.add(comboBox, BorderLayout.NORTH);    frame.setSize(300, 200);    frame.setVisible(true);  }}

  例 6:编辑 JComboBox框,实现颜色切换

import java.awt.BorderLayout;import java.awt.Color;import java.awt.Component;import java.awt.Dimension;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.ComboBoxEditor;import javax.swing.DefaultListCellRenderer;import javax.swing.JButton;import javax.swing.JColorChooser;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JList;import javax.swing.ListCellRenderer;import javax.swing.border.LineBorder;import javax.swing.event.EventListenerList;class ColorComboBoxEditor implements ComboBoxEditor {  final protected JButton editor;  protected EventListenerList listenerList = new EventListenerList();  public ColorComboBoxEditor(Color initialColor) {    editor = new JButton("");    editor.setBackground(initialColor);    ActionListener actionListener = new ActionListener() {      public void actionPerformed(ActionEvent e) {        Color currentBackground = editor.getBackground();        Color color = JColorChooser.showDialog(editor, "Color Chooser", currentBackground);        if ((color != null) && (currentBackground != color)) {          editor.setBackground(color);          fireActionEvent(color);        }      }    };    editor.addActionListener(actionListener);  }  public void addActionListener(ActionListener l) {    listenerList.add(ActionListener.class, l);  }  public Component getEditorComponent() {    return editor;  }  public Object getItem() {    return editor.getBackground();  }  public void removeActionListener(ActionListener l) {    listenerList.remove(ActionListener.class, l);  }  public void selectAll() {  }  public void setItem(Object newValue) {    if (newValue instanceof Color) {      Color color = (Color) newValue;      editor.setBackground(color);    } else {      try {        Color color = Color.decode(newValue.toString());        editor.setBackground(color);      } catch (NumberFormatException e) {      }    }  }  protected void fireActionEvent(Color color) {    Object listeners[] = listenerList.getListenerList();    for (int i = listeners.length - 2; i >= 0; i -= 2) {      if (listeners[i] == ActionListener.class) {        ActionEvent actionEvent = new ActionEvent(editor, ActionEvent.ACTION_PERFORMED, color            .toString());        ((ActionListener) listeners[i + 1]).actionPerformed(actionEvent);      }    }  }}class ColorCellRenderer implements ListCellRenderer {  protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();  // Width doesn‘t matter as the combo box will size  private final static Dimension preferredSize = new Dimension(0, 20);  public Component getListCellRendererComponent(JList list, Object value, int index,      boolean isSelected, boolean cellHasFocus) {    JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,        isSelected, cellHasFocus);    if (value instanceof Color) {      renderer.setBackground((Color) value);    }    if(cellHasFocus || isSelected){      renderer.setBorder(new LineBorder(Color.DARK_GRAY));    }else{      renderer.setBorder(null);    }    renderer.setPreferredSize(preferredSize);    return renderer;  }}public class ColorComboBoxEditorRendererDemo {  public static void main(String args[]) {    Color colors[] = { Color.BLACK, Color.BLUE, Color.GREEN, Color.RED, Color.WHITE, Color.YELLOW };    JFrame frame = new JFrame("Color JComboBox");    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    final JComboBox comboBox = new JComboBox(colors);    comboBox.setEditable(true);    comboBox.setRenderer(new ColorCellRenderer());    Color color = (Color) comboBox.getSelectedItem();    ComboBoxEditor editor = new ColorComboBoxEditor(color);    comboBox.setEditor(editor);    frame.add(comboBox, BorderLayout.NORTH);    final JLabel label = new JLabel();    label.setOpaque(true);    label.setBackground((Color) comboBox.getSelectedItem());    frame.add(label, BorderLayout.CENTER);    ActionListener actionListener = new ActionListener() {      public void actionPerformed(ActionEvent actionEvent) {        Color selectedColor = (Color) comboBox.getSelectedItem();        label.setBackground(selectedColor);      }    };    comboBox.addActionListener(actionListener);    frame.setSize(300, 200);    frame.setVisible(true);  }}

  例 7:改变JComboBox旁边按钮样式

import java.awt.BorderLayout;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JComponent;import javax.swing.JFrame;import javax.swing.plaf.ComboBoxUI;import javax.swing.plaf.ComponentUI;import javax.swing.plaf.basic.BasicArrowButton;import javax.swing.plaf.basic.BasicComboBoxUI;public class PopupComboSample {  public static void main(String args[]) {    String labels[] = { "A", "B", "C", "D", "E", "F", "G" };    JFrame frame = new JFrame("Popup JComboBox");    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    JComboBox comboBox = new JComboBox(labels);    comboBox.setUI((ComboBoxUI) MyComboBoxUI.createUI(comboBox));    frame.add(comboBox, BorderLayout.NORTH);    frame.setSize(300, 200);    frame.setVisible(true);  }  static class MyComboBoxUI extends BasicComboBoxUI {    public static ComponentUI createUI(JComponent c) {      return new MyComboBoxUI();    }    protected JButton createArrowButton() {      JButton button = new BasicArrowButton(BasicArrowButton.WEST);      return button;    }  }}

  

Swing开发之JComboBox篇