`
zeyuphoenix
  • 浏览: 55693 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

JCombobox组合框效果实现

 
阅读更多
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="ProgId" content="Word.Document"> <meta name="Generator" content="Microsoft Word 12"> <meta name="Originator" content="Microsoft Word 12"> <link rel="File-List" href="file:///C:%5CDOCUME%7E1%5Cphoenix%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_filelist.xml"> <link rel="Edit-Time-Data" href="file:///C:%5CDOCUME%7E1%5Cphoenix%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_editdata.mso"> <!--[if !mso]> <style> v":* {behavior:url(#default#VML);} o":* {behavior:url(#default#VML);} w":* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} </style> <![endif]--><link rel="themeData" href="file:///C:%5CDOCUME%7E1%5Cphoenix%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_themedata.thmx"> <link rel="colorSchemeMapping" href="file:///C:%5CDOCUME%7E1%5Cphoenix%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_colorschememapping.xml"> <!--[if gte mso 9]><xml> Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE MicrosoftInternetExplorer4 </xml><![endif]--><!--[if gte mso 9]><![endif]--><style> <!-- /* 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;} --> </style> <!--[if gte mso 10]> <style> /* Style Definitions */ table.MsoNormalTable { mso-style-parent:""; font-size:10.5pt; font-family:"Calibri","serif"; mso-bidi-font-family:"Times New Roman";} </style> <![endif]-->

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

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

先看Sun给的官方的例子:

<!--[if gte vml 1]> <![endif]-->



<!--[if gte vml 1]> <![endif]-->

具体的实现很简单:

        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,JComboboxRenderer需要实现ListCellRenderer接口.

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



<!--[if gte vml 1]> <![endif]-->

<!--[if gte vml 1]> <![endif]-->

具体的实现其实和普通的一样,先把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可以设置成按钮的样式.

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

<!--[if gte vml 1]> <![endif]-->

重写UI

    privatestaticclass MyComboBoxUI extends BasicComboBoxUI {

       publicstatic ComponentUI createUI(JComponent c) {

           returnnew MyComboBoxUI();

        }

       @Override

       protected JButton createArrowButton() {

           JButton button = new BasicArrowButton(BasicArrowButton.EAST);

           return button;

       }

    }

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

    JComboBox comboBox = new JComboBox(labels);

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

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

先看完成后的界面:

<!--[if gte vml 1]> <![endif]-->



<!--[if gte vml 1]> <![endif]-->

工程的目录结构如下:

<!--[if gte vml 1]> <![endif]-->

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

/**

 *theinterfacethattheJComboBoxcanhavelineenable.

*/

publicinterface LineEnable {

    /**

     *setbean.

     *@paramisLineEnable

     *            isLineenable

     */

    publicvoid setLineEnabled(boolean isLineEnable);

    /**

     *getbean.

     *@returnisLineenable

     */

    publicboolean isLineEnabled();

}

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

/**

 *theinterfacethattheJComboBoxcanselectenable.

*/

publicinterface SelectEnable {

    /**

     *setbean.

     *@paramisSelectEnable

     *            isSelectenable

     */

    publicvoid setSelectEnabled(boolean isSelectEnable);

    /**

     *getbean.

     *@returnisSelectenable

     */

    publicboolean isSelectEnabled();

}

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

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

/**

 *theitemsthatyouwanttoshowinJComboBox.

*/

publicclass MyComboBoxItem implements SelectEnable, LineEnable {

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

它具有3个属性:

    /**

     *JComboBoxitems.

     */

    private Object comboxItem = null;

    /**

     *isselectenabled.

     */

    booleanisSelectEnabled = true;

    /**

     *islineenabled.

     */

    booleanisLineEnabled = 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 < 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;

       }

    }

接下来的类就是设置JComboboxUI,

/**

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

}

然后在UInew BasicComboPopup(comboBox) {

popup.getAccessibleContext().setAccessibleParent(comboBox);

就可以了.

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

/**

 *theJComboBoxthatithavesomeownmethod.

*/

publicclass MyComboBox extends JComboBox {

在构造函数里设置UI

setUI(new MyComboBoxUI());

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

    public Dimension getPopupSize() {

       Dimension size = getSize();

       // reset size.

       if (popupWidth < 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控件使用了.

分享到:
评论

相关推荐

    Java获取Java所在的根目录.rar

    可以在Windows和LINUX两个平台中使用,都可以得到JAVA所在的路径,程序使用JComboBox组合框组件来存放获得的根目录信息,如在Linux 和Unix 系统下组合框只有一项即“/”,截图是Windows平台的效果。

    Java高级程序设计:第12章-基本控件.pptx

    组合框JComboBox;组合框JComboBox—事件;public class Test4 extends JFrame implements ActionListener { String[] items = { "篮球", "足球", "乒乓球" }; JComboBox&lt;String&gt; box = new JComboBox(items); Test4()...

    编程技能训练与等级考试辅导:组合框与列表框.pptx

    16.3 组合框与列表框;组合框也称为选择列表(choice list)或是下拉列表(drop-down list),它包含一个条目列表,用户能从中进行选择。 属性:都是从JComponent等父辈继承来的。 构造方法与一般方法: JComboBox() ...

    java swing综合程序

    一步一步地实现菜单栏(JMenuBar)工具栏(JPopupMenu)组合框(JComboBox)复选框(JCheckBox)单选按钮(JRadioButton)文本域的综合应用(三) 源程序

    Java播放wav音频功能的实现代码.rar

      //把文件选择组合框、控制面板、状态栏标签加入到窗口内容窗格   container.add(jcbFiles, BorderLayout.NORTH);   container.add(controlPanel, BorderLayout.CENTER);   container.add(status, ...

    编程技能训练与等级考试辅导:综合应用.pptx

    JComboBox组合框的基本属性、方法 ;? JMenuBar、JMenu、JMenuItem菜单组件的基本属性、方法(难点) ? Font类、Color类、ImageIcon类基本方法(难点) ActionKevent事件、KeyEvent事件、Mouse事件、Window事件处理...

    Java Swing中的JButton、JComboBox、JList和JColorChooser组件使用案例

    主要介绍了Java Swing中的按钮(JButton)、组合框(JComboBox)、下拉列表(JList)和颜色选择器(JColorChooser)组件使用案例,需要的朋友可以参考下

    Swing组件下载(常用组件)

    组合框:JComboBox 列表:JList 文本字段:JTextField 文本区域:JTextArea 滚动条:JScrollBar 滑块:JSlider 进度栏:JProgressBar 格式化字段:JFormattedTextField 口令字段:JPasswordField Spinner:JSpinner ...

    多媒体处理其中有多个多媒体的作用技术处理

    //把文件选择组合框、控制面板、状态栏标签加入到窗口内容窗格 container.add(jcbFiles, BorderLayout.NORTH); container.add(controlPanel, BorderLayout.CENTER); container.add(status, BorderLayout....

    学生管理系统

    //创建一个组合框对象 public DengLuJieMian() { this.setTitle("学生信息管理系统"); //设置窗口标题 this.setLayout(null); //设置窗口布局管理器 JLUserName.setBounds(100,40,100,20); //设置姓名标签的...

    Java获取系统根目录

    摘要:Java源码,系统相关,获取目录,根目录 ...利用一个组合框组件(JComboBox)来存放所有获得的根目录,如在Linux 和Unix 系统下组合框只有一项即“/”,截图是在Windows 系统下的实现效果。 运行环境:Java/Eclipse

    javaswing项目源码-Java-Graphical-User-Interface-Swing-Tutorial-Netbeans-IDE

    组合框 浏览图像文件并使用Java Swing在Jlabel上显示它 如何从计算机显示图像并将图像插入到JTable单元中-Java GUI-NetBeans IDE教程 如何在Java中显示从JTable单元到JLabel的图像(Java源代码) Java-如何使用...

    Java开发技术大全 电子版

    14.8.8组合框(JComboBox)使用示例506 14.8.9表格(Jtable)使用示例508 14.8.10树(JTree)使用示例518 14.8.11菜单使用示例523 14.9布局管理527 14.9.1流式布局(FlowLayout)回顾527 14.9.2边框布局...

    疯狂JAVA讲义

    学生提问:使用组合关系来实现复用时,需要创建两个Animal对象,是不是意味着使用组合关系时系统开销更大? 159 5.9 初始化块 159 5.9.1 使用初始化块 160 5.9.2 初始化块和构造器 161 5.9.3 静态初始化块 162 ...

    javaSE代码实例

    15.4.2 基于接口实现的匿名内部类 335 15.4.3 匿名内部类的初始化 337 15.4.4 匿名内部类作用的体现 337 15.5 理解内部类 339 15.6 内部接口 340 15.6.1 定义在类中的内部接口 340 15.6.2 定义在接口中...

    java初学者必看

    13.3.4 组合框(JComboBox) 13.3.5 进程条(JprogressBar) 13.3.6 表格(JTable) 13.3.7 树(JTree) 13.3.8 文本框(JTextField)与文本区(JTextArea) 13.4 布局管理器 13.4.1 FlowLayout布局管理器 13.4.2 ...

Global site tag (gtag.js) - Google Analytics