My JList that I extended to let the user drag-and-drop reorder it (used Reorder a JList with Drag-and-Drop and Use drag and drop to reorder a list) but it gives me a weird outcome. Instead of giving me my custom JComponent
, it gives me the .toString()
value of it. I set the model of my custom JList
to DefaultListModel<JComponent>
thinking it would work but it didn't.
You need to create a custom CellRenderer
for the object you want to render. By default, JList will show the toString value of the component (because DefaultListCellRenderer extends 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;
}
If you don't actually want to render a string, create an implementation of CellRenderer that returns the component you want to render.