swing的列表框

JList、JComboBox实现列表框: 无论从哪个角度来看,JList和JComboBox都是极其相似的,它们都有一个列表框,只是JComboBox的列表框需要以下拉方式显示出来; JList和JComboBox都可以通过调用setRendererO方法来改变列表项的表现形式。甚至维护这两个组件的Model都是相似的, JList使用ListModel, JComboBox使用ComboBoxModel,而ComboBoxModel是ListModel的子类

我们要学的列表框有两种,如下 1、JList列表框:不需要任何操作,默认就是展开的,我们可以看到该列表框的多个条目(条目也就是列表项) 2、JComboBox下拉选中列表框:需要用户点击小按钮才会展示改列表

 

使用JList或JComboBox实现简单列表框的步骤:

 

第一步:创建JList或JComboBox对象,如下是两种列表框的构造方法:

JList(final E[] listData):创建JList对象,把listData数组中的每项内容转换成一个列表项展示 JList(final Vector<? extends E> listData):创建JList对象,把listData数组中的每项内容转换成一个列表项展示,其中Vector是集合 JComboBox(E[] items):JComboBox(Vector items)

 

第二步:设置JList或JComboBox的外观行为,如下是两种列表框的成员方法:

【JList】 addSelectionInterval(int anchor, int lead):在已经选中列表项的基础上,增加选中从anchor到lead索引范围内的所有列表项 setFixedCellHeight(int height)/setFixedCellWidth(int width):设置列表项的高度和宽度 setLayoutOrientation(int layoutOrientation):设置列表框的布局方向 setSelectedIndex(int index):设置默认选中项 setSelectedIndices(int[] indices):设置默认选中的多个列表项 setSelectedValue(Object anObject,boolean shouldScroll):设置默认选中项,并滚动到该项显示 setSelectionBackground(Color selectionBackground):设置选中项的背景颜色 setSelectionForeground(Color selectionForeground):设置选中项的前景色 setSelectionInterval(int anchor, int lead):设置从anchor到lead范围内的所有列表项被选中 setSelectionMode(int selectionMode):设置选中模式,默认没有限制,也可以设置为单选或者区域选中 setVisibleRowCount(int visibleRowCount):设置列表框的可视高度,即一页显示多少行列表项

【JComboBox】 setEditable(boolean aFlag):设置是否可以直接修改或编辑列表文本框的值,默认为不可以 setMaximumRowCount(int count):设置列表框的可视高度,即一页显示多少行列表项 setSelectedIndex(int anIndex):设置默认选中项 setSelectedItem(Object anObject):根据列表项的值,设置默认选中项

 

第三步:设置监听器,监听列表框的列表项的变化 JList通过addListSelectionListener完成,JComboBox通过addItemListener完成

 

swing的列表框_练习