我扩展了我的JList,让用户拖放重新排序(使用拖放重新排序JList和使用拖放重新排列列表),但它给了我一个奇怪的结果。它没有给我自定义的JComponent
,而是给我它的.toString()
值。我将自定义JList
的模型设置为DefaultListModel<JComponent>
,以为它可以工作,但它没有。
您需要为要渲染的对象创建一个自定义CellRenderer
。默认情况下,JList将显示组件的toString值(因为DefaultListCellRenderer扩展了JLabel)。
class MyRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(...);
setText(getValue(value)); // where getValue is some method you implement that gets the text you want to render for the component
return c;
}
如果您实际上不想渲染字符串,请创建CellRenderer的实现,该实现返回要渲染的组件。