Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word wrap in JList items

I have a JList with very long item names that cause the horizontal scroll-bar to appear in scroll-pane.

Is there anyway that I can word wrap so that the whole whole item name appears in 2 rows yet can be selected in one click? I.E it should still behave as a single item but be displayed in two rows.


Here is what I did after seeing the example below

I added a new class to my project MyCellRenderer and then I went added MyList.setCellRenderer(new MyCellRenderer(80)); in the post creation code of my List. Is there anything else I need to do?

like image 861
koool Avatar asked Nov 19 '11 20:11

koool


1 Answers

Yep, using Andrew's code, I came up with something like this:

import java.awt.Component;
import javax.swing.*;

public class JListLimitWidth {
   public static void main(String[] args) {
      String[] names = { "John Smith", "engelbert humperdinck",
            "john jacob jingleheimer schmidt" };
      MyCellRenderer cellRenderer = new MyCellRenderer(80);
      JList list = new JList(names);
      list.setCellRenderer(cellRenderer);
      JScrollPane sPane = new JScrollPane(list);
      JPanel panel = new JPanel();
      panel.add(sPane);
      JOptionPane.showMessageDialog(null, panel);

   }
}

class MyCellRenderer extends DefaultListCellRenderer {
   public static final String HTML_1 = "<html><body style='width: ";
   public static final String HTML_2 = "px'>";
   public static final String HTML_3 = "</html>";
   private int width;

   public MyCellRenderer(int width) {
      this.width = width;
   }

   @Override
   public Component getListCellRendererComponent(JList list, Object value,
         int index, boolean isSelected, boolean cellHasFocus) {
      String text = HTML_1 + String.valueOf(width) + HTML_2 + value.toString()
            + HTML_3;
      return super.getListCellRendererComponent(list, text, index, isSelected,
            cellHasFocus);
   }

}
like image 151
Hovercraft Full Of Eels Avatar answered Sep 24 '22 22:09

Hovercraft Full Of Eels