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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With