当JList
渲染本身时,它会询问ListModel
它应该显示的元素。对于它调用的每个元素javax.swing.ListCellRenderer
来提供一个渲染组件。然后它绘制组件。就这样。渲染组件不绑定到它渲染的元素状态。
的 javadocListCellRenderer
说:
标识可用作“橡皮图章”以在JList
.
所以你的第二个假设是正确的。
一看javax.swing.plaf.BasicListUI
就知道:
protected void paintCell(Graphics g, int row, Rectangle rowBounds,
ListCellRenderer cellRenderer, ListModel dataModel,
ListSelectionModel selModel, int leadIndex) {
Object value = dataModel.getElementAt(row);
boolean cellHasFocus = list.hasFocus() && (row == leadIndex);
boolean isSelected = selModel.isSelectedIndex(row);
Component rendererComponent = cellRenderer
.getListCellRendererComponent(list, value, row, isSelected,
cellHasFocus);
int cx = rowBounds.x;
int cy = rowBounds.y;
int cw = rowBounds.width;
int ch = rowBounds.height;
if (isFileList) {
// Shrink renderer to preferred size. This is mostly used on Windows
// where selection is only shown around the file name, instead of
// across the whole list cell.
int w = Math
.min(cw, rendererComponent.getPreferredSize().width + 4);
if (!isLeftToRight) {
cx += (cw - w);
}
cw = w;
}
rendererPane.paintComponent(g, rendererComponent, list, cx, cy, cw, ch,
true);
}