我扩展的JList让用户拖放对它进行重新排序(使用Reorder a JList with Drag-and-Drop和Use drag and drop to reorder a list)但它给了我一个奇怪的结果。它没有给我自定义JComponent
,而是给了我.toString()
的价值。我将自定义JList
的模型设置为DefaultListModel<JComponent>
,认为它会起作用,但事实并非如此。
答案 0 :(得分:5)
您需要为要渲染的对象创建自定义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实现,返回您要渲染的组件。