---
title: "JCombobox组合框效果实现"
author: "zeyuphoenix"
date: "2010-04-12T00:43:00Z"
tags: []
slug: "jcombobox"
draft: false
lastmod: "2015-03-18T19:32:27Z"
id: 2193702
url: "https://zeyuphoenix.iteye.com/blog/2193702"
---

&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; &lt;meta name="ProgId" content="Word.Document"&gt; &lt;meta name="Generator" content="Microsoft Word 12"&gt; &lt;meta name="Originator" content="Microsoft Word 12"&gt; &lt;link rel="File-List" href="file:///C:%5CDOCUME%7E1%5Cphoenix%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip\_filelist.xml"&gt; &lt;link rel="Edit-Time-Data" href="file:///C:%5CDOCUME%7E1%5Cphoenix%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip\_editdata.mso"&gt; &lt;!--\[if !mso]&gt; &lt;style&gt; v":* {behavior:url(#default#VML);} o":* {behavior:url(#default#VML);} w":* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} &lt;/style&gt; &lt;!\[endif]--&gt;&lt;link rel="themeData" href="file:///C:%5CDOCUME%7E1%5Cphoenix%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip\_themedata.thmx"&gt; &lt;link rel="colorSchemeMapping" href="file:///C:%5CDOCUME%7E1%5Cphoenix%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip\_colorschememapping.xml"&gt; &lt;!--\[if gte mso 9]&gt;&lt;xml&gt; Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE MicrosoftInternetExplorer4 &lt;/xml&gt;&lt;!\[endif]--&gt;&lt;!--\[if gte mso 9]&gt;&lt;!\[endif]--&gt;&lt;style&gt; &lt;!-- /* Font Definitions \*/ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1;} @font-face {font-family:"Cambria Math"; panose-1:2 4 5 3 5 4 6 3 2 4;} @font-face {font-family:""@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1;} /* Style Definitions \*/ p.MsoNormal, li.MsoNormal, div.MsoNormal { mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; font-size:10.5pt; font-family:"Times New Roman","serif";} .MsoChpDefault { font-size:10.0pt; mso-ascii-font-family:"Times New Roman"; mso-hansi-font-family:"Times New Roman";} /* Page Definitions \*/ @page {} @page Section1 {size:595.3pt 841.9pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; layout-grid:15.6pt;} div.Section1 {page:Section1;} --&gt; &lt;/style&gt; &lt;!--\[if gte mso 10]&gt; &lt;style&gt; /* Style Definitions \*/ table.MsoNormalTable { mso-style-parent:""; font-size:10.5pt; font-family:"Calibri","serif"; mso-bidi-font-family:"Times New Roman";} &lt;/style&gt; &lt;!\[endif]--&gt;

JCombobox是Swing中比较常用的控件,它显示一个项列表,扩展的是ListModel接口的模型，它的显示绘制器通过实现ListCellBenderer接口来绘制列表单元,下面介绍 ①普通应用例子;②显示图片选项框例子;③修改下拉按钮的例子;④下拉框可选与否的例子.

①

对于普通情况下使用JCombobox,没有什么注意事项,只需要把JCombobox new出来,设置它的Model的值就可以了.

先看Sun给的官方的例子：

&lt;!--\[if gte vml 1]&gt; &lt;!\[endif]--&gt;

![](http://www.blogjava.net/images/blogjava_net/zeyuphoenix/341.jpg)  
![](http://www.blogjava.net/images/blogjava_net/zeyuphoenix/342.jpg)

&lt;!--\[if gte vml 1]&gt; &lt;!\[endif]--&gt;

具体的实现很简单:

        String\[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };

        //Create the combo box, select the item at index 4.

        JComboBox petList = **new** JComboBox(petStrings);

        petList.setSelectedIndex(4);

        petList.addActionListener(**this**);

也可以通过petList.setEditable(**true**);设置是否可以编辑.对于Action的处理和普通的一样.

②

JCombobox默认下拉显示和显示项是文本,为了显示其它内容比如图片或者更复杂的东西,则需要设置新的Renderer,JCombobox的Renderer需要实现ListCellRenderer接口.

这个也比较简单,Sun官方也给了例子：

![](http://www.blogjava.net/images/blogjava_net/zeyuphoenix/343.jpg)  
![](http://www.blogjava.net/images/blogjava_net/zeyuphoenix/344.jpg)

&lt;!--\[if gte vml 1]&gt; &lt;!\[endif]--&gt;

&lt;!--\[if gte vml 1]&gt; &lt;!\[endif]--&gt;

具体的实现其实和普通的一样,先把JCombobox new出来,在使用setRenderer方法设置自己定义的Renderer就可以了.

    // Create the combo box.

    JComboBox petList = **new** JComboBox(intArray);

    ComboBoxRenderer renderer = **new** ComboBoxRenderer();

    renderer.setPreferredSize(**new** Dimension(200, 130));

    petList.setRenderer(renderer);

当然这个Renderer是实现了ListCellRenderer接口的.

**privateclass** ComboBoxRenderer **extends** JLabel **implements** ListCellRenderer {

这样要是实现接口的方法：

    /*

    * This method finds the image and text corresponding to the selected

    * value and returns the label, set up to display the text and image.

    \*/

@Override

**public** Component getListCellRendererComponent(JList list, Object value, **int** index, **boolean** isSelected, **boolean** cellHasFocus) {

然后然后this就是继承的JLabel了,对它可以设置属性了:

    setIcon(icon);

    setText(pet);

最后把设置好的控件返回就可以了,

**returnthis**;

当然你也可以设置更复杂的控件,比如继承JButton可以设置成按钮的样式.

③

Swing的MVC模式非常的好,当你需要更改控件的显示的时候只需要继承控件的基本UI,重写你需要重写的部位就可以了，这儿想下拉框的按钮不显示向下的箭头,只需要继承BasicComboBoxUI,重写createArrowButton方法就可以了.

![](http://www.blogjava.net/images/blogjava_net/zeyuphoenix/345.jpg)

&lt;!--\[if gte vml 1]&gt; &lt;!\[endif]--&gt;

重写UI

    **privatestaticclass** MyComboBoxUI **extends** BasicComboBoxUI {

       **publicstatic** ComponentUI createUI(JComponent c) {

           **returnnew** MyComboBoxUI();

        }

       @Override

       **protected** JButton createArrowButton() {

           JButton button = **new** BasicArrowButton(BasicArrowButton.*EAST*);

           **return** button;

       }

    }

当你需要修改JCombobox的UI的时候,只需要调用setUI方法就可以了.

    JComboBox comboBox = **new** JComboBox(labels);

    comboBox.setUI((ComboBoxUI) MyComboBoxUI.*createUI*(comboBox));

④

对于修改JCombobox的显示可以从两个方向考虑,一个是修改MetalComboBoxUI,一个是继承ListCellRenderer.在通过设置UI和Renderer使界面修改.

先看完成后的界面:

&lt;!--\[if gte vml 1]&gt; &lt;!\[endif]--&gt;

![](http://www.blogjava.net/images/blogjava_net/zeyuphoenix/346.jpg)  
![](http://www.blogjava.net/images/blogjava_net/zeyuphoenix/347.jpg)

&lt;!--\[if gte vml 1]&gt; &lt;!\[endif]--&gt;

工程的目录结构如下:

![](http://www.blogjava.net/images/blogjava_net/zeyuphoenix/348.jpg)

&lt;!--\[if gte vml 1]&gt; &lt;!\[endif]--&gt;

先设置JCombobox下拉框是否有线,为了使以后扩展容易,设置为接口:

/\**

 \*theinterfacethattheJComboBoxcanhavelineenable.

\*/

**publicinterface** LineEnable {

    /\**

     \*setbean.

     \***@param**isLineEnable

     *            isLineenable

     \*/

    **publicvoid** setLineEnabled(**boolean** isLineEnable);

    /\**

     \*getbean.

     \***@return**isLineenable

     \*/

    **publicboolean** isLineEnabled();

}

同样的对于JCombobox下拉框是否可以选择也设置为接口：

/\**

 \*theinterfacethattheJComboBoxcanselectenable.

\*/

**publicinterface** SelectEnable {

    /\**

     \*setbean.

     \***@param**isSelectEnable

     *            isSelectenable

     \*/

    **publicvoid** setSelectEnabled(**boolean** isSelectEnable);

    /\**

     \*getbean.

     \***@return**isSelectenable

     \*/

    **publicboolean** isSelectEnabled();

}

当然需要别的属性,比如颜色、形状等也可以再设置相同的接口.

对于JCombobox的没一个Item,都可以通过实现这些接口获得相应的显示:

/\**

 \*theitemsthatyouwanttoshowinJComboBox.

\*/

**publicclass** MyComboBoxItem **implements** SelectEnable, LineEnable {

对于特殊的JCombobox设置Item时,设置MyComboBoxItem就可以使Item具有选择可否和是否是线的样式.

它具有3个属性:

    /\**

     \*JComboBoxitems.

     \*/

    **private** Object comboxItem = **null**;

    /\**

     \*isselectenabled.

     \*/

    **boolean**isSelectEnabled = **true**;

    /\**

     \*islineenabled.

     \*/

    **boolean**isLineEnabled = **false**;

可以通过设置它们得到JCombobox样式，这个类就是一个简单的Java Bean.

然后就是设置JCombobox的选项的显示,实现ListCellRenderer接口,通过对组件的重写设置描绘它的新属性:

/\**

 \*JComboBoxcellrenderer.

\*/

**publicclass** MyComboBoxRenderer **extends** JLabel **implements** ListCellRenderer, ActionListener {

重写它的方法：

    /\**

     \*Returnacomponentthathasbeenconfiguredtodisplaythespecified

     \*value.

     \*/

    @Override

    **public** Component getListCellRendererComponent(JList list, Object value, **int** index, **boolean** isSelected, **boolean** cellHasFocus) {

先设置它的显示

String item = (value == **null**) ? "" : value.toString();

再设置是否是线：

       **if** (((LineEnable) value).isLineEnabled()) {

           **returnnew** JSeparator(JSeparator.*HORIZONTAL*);

       }

接着设置tooltip,提示是否可以显示:

        **if** (-1 &lt; index) {

              **if** (((SelectEnable) value).isSelectEnabled()) {

                  list.setToolTipText("You select is : " + item);

              } **else** {

                  list.setToolTipText("You cn't select : " + item

                         + ", It select unEnable.");

              }

       }

最后设置是否可以显示:

**if** (!((SelectEnable) value).isSelectEnabled()) {

           setBackground(list.getBackground());     setForeground(UIManager.*getColor*("Label.disabledForeground"));

       }

然后还是需要设置某些选择不可选时候的设置不可选:

    /\**

     \*Thelistenerinterfaceforreceivingactionevents.

     \*/

    **publicvoid** actionPerformed(ActionEvent e) {

       Object tempItem = combox.getSelectedItem();

当是线的Item不可选,返回之前选项

       **if** (((LineEnable) tempItem).isLineEnabled()) {

           combox.setSelectedItem(currentItem);

       } **else** {

           currentItem = tempItem;

       }

当是不可选的Item不可选,返回之前选项

       **if** (!((SelectEnable) tempItem).isSelectEnabled()) {

           combox.setSelectedItem(currentItem);

       } **else** {

           currentItem = tempItem;

       }

    }

接下来的类就是设置JCombobox的UI了,

/\**

 \*MetalUIforJComboBox.

\*/

**publicclass** MyComboBoxUI **extends** MetalComboBoxUI {

这里的UI设置主要是设置选择不可选的项时清除,并对JCombobox的下拉的菜单设置

/\**

\*showthepopupmenusize.

\*/

@Override

**publicvoid** show() {

    Dimension popupSize = ((MyComboBox) comboBox).getPopupSize();

    // reset size.

   popupSize.setSize(popupSize.width, getPopupHeightForRowCount(comboBox.getMaximumRowCount()));

              Rectangle popupBounds = computePopupBounds(0, comboBox

              .getBounds().height, popupSize.width, popupSize.height);

    // set max and mini size.

    scroller.setMaximumSize(popupBounds.getSize());

    scroller.setPreferredSize(popupBounds.getSize());

    scroller.setMinimumSize(popupBounds.getSize());

    // Invalidates the container.

    list.invalidate();

    // set select.

    **int** selectedIndex = comboBox.getSelectedIndex();

    **if** (selectedIndex == -1) {

        list.clearSelection();

    } **else** {

       list.setSelectedIndex(selectedIndex);

    }

    list.ensureIndexIsVisible(list.getSelectedIndex());

    setLightWeightPopupEnabled(comboBox.isLightWeightPopupEnabled());

    // show it.

    show(comboBox, popupBounds.x, popupBounds.y);

}

然后在UI的**new** BasicComboPopup(comboBox) {

popup.getAccessibleContext().setAccessibleParent(comboBox);

就可以了.

最后的类就是自己的MyComboBox了,这个类其实也可以不要,只需要你在新建自己特殊的JCombobox时,不要忘记设置UI和传入的Item是MyComboBoxItem就可以了,这里为了方便自己实现了,以后使用时只需要New MyComboBox就可以了.

/\**

 \*theJComboBoxthatithavesomeownmethod.

\*/

**publicclass** MyComboBox **extends** JComboBox {

在构造函数里设置UI：

setUI(**new** MyComboBoxUI());

另外为了显示宽度合适,它提供了设置popupWidth的方法：

    **public** Dimension getPopupSize() {

       Dimension size = getSize();

       // reset size.

       **if** (popupWidth &lt; 1) {

           popupWidth = size.width;

       }

       **returnnew** Dimension(popupWidth, size.height);

    }

这样一个属于自己的JComboBox就设置完成了,使用方法如下:

MyComboBoxItem \[] items = { **new** MyComboBoxItem("Astart"),

                  **new** MyComboBoxItem("BGold", **true**, **true**),

                  **new** MyComboBoxItem("ilove", **false**),

                  **new** MyComboBoxItem("fire your game", **true**),

                  **new** MyComboBoxItem("", **true**, **true**),

                  **new** MyComboBoxItem("NIHA", **false**),

                  **new** MyComboBoxItem("生活"),

                  **new** MyComboBoxItem("", **false**, **true**) };

JComboBox jComboBox = **new** MyComboBox(items);

jComboBox.setRenderer(**new** MyComboBoxRenderer(jComboBox));

以后就可以当做一个普通的Java控件使用了.