JCombobox是Swing中比较常用的控件,它显示一个项列表,扩展的是ListModel接口的模型,它的显示绘制器通过实现ListCellBenderer接口来绘制列表单元,下面介绍 ①普通应用例子;②显示图片选项框例子;③修改下拉按钮的例子;④下拉框可选与否的例子.
①
对于普通情况下使用JCombobox,没有什么注意事项,只需要把JCombobox new出来,设置它的Model的值就可以了.
先看Sun给的官方的例子:
具体的实现很简单:
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官方也给了例子:
具体的实现其实和普通的一样,先把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<