java jcombobox 样式_JCombobox组合框效果实现

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

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

先看Sun给的官方的例子:

341.jpg

342.jpg

具体的实现很简单:

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

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

JComboBox petList =newJComboBox(petStrings);

petList.setSelectedIndex(4);

petList.addActionListener(this);

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

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

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

343.jpg

344.jpg

具体的实现其实和普通的一样,先把JCombobox

new出来,在使用setRenderer方法设置自己定义的Renderer就可以了.

// Create the combo box.

JComboBox petList =newJComboBox(intArray);

ComboBoxRenderer renderer =newComboBoxRenderer();

renderer.setPreferredSize(newDimension(200, 130));

petList.setRenderer(renderer);

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

privateclassComboBoxRendererextendsJLabelimplementsListCellRenderer {

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

/*

* 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

publicComponent<

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值