String[] months = {"1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"}
monthList = new jlist(months)
monthList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)// 设置选择模式
monthList.setFixedCellHeight(20) // 设置选项高度
monthList.setVisibleRowCount(6) // 设置可见个数
monthList.setSelectionBackground(Color.GREEN) // 设置被选中项的背景颜色
monthList.setSelectionForeground(Color.RED)// 设置被选中项的字体颜色
默认的就是JLabel了。如果你要该我给你一个样板。
public class myList extends JPanel {
private static final long serialVersionUID = 1L
JList mList
DefaultListModel mode
public myList() {
setLayout(new BorderLayout())
mode = new DefaultListModel()
for (int i = 0i <10i++) {
mode.addElement("123")
}
mList = new JList(mode)
mList.setCellRenderer(new MyCellRenderer())
add(new JScrollPane(mList), BorderLayout.CENTER)
}
public static void main(String[] args) {
JFrame jf = new JFrame()
jf.add(new myList(), BorderLayout.CENTER)
jf.pack()
jf.setVisible(true)
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
}
class MyCellRenderer extends JButton implements ListCellRenderer {
public MyCellRenderer() {
setOpaque(true)
}
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
setText(value.toString())
Color background
Color foreground
// check if this cell represents the current DnD drop location
JList.DropLocation dropLocation = list.getDropLocation()
if (dropLocation != null &&!dropLocation.isInsert() &&dropLocation.getIndex() == index) {
background = Color.BLUE
foreground = Color.WHITE
// check if this cell is selected
} else if (isSelected) {
background = Color.RED
foreground = Color.WHITE
// unselected, and not the DnD drop location
} else {
background = Color.WHITE
foreground = Color.BLACK
}
setBackground(background)
setForeground(foreground)
return this
}
}
}
listCellRenderer是控制显示的,我这里是button,你也可以换成别的,不建议使用jPanel,panel无法显示字体,所以你要自己弄个控件显示。
Model只负责保存数据,和界面无关,不要把界面也放到这里了。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)