Arka Majumdar Arka Majumdar - 2 years ago 146
Java Question

Java JList unwanted toString() conversion

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

, it gives me the
value of it. I set the model of my custom
thinking it would work but it didn't.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download