I have a JList populating a list of strings
String[] values = new String[] {"David Pickwell", "-", "Tico", "-", "Jack Wilshere", "-","Nick Johanson"};
I have been using this method for years to add JSeparator to the GUI with a custom ListCellRender. So, it will check if the current string equals to "-", it will render a separator.
public Component getListCellRendererComponent(JList<? extends Object> list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
...
String str = (value == null) ? "" : value.toString();
if (SEPARATOR.equals(str)) { // What I am talking about
return separator;
}
...
return this;
}
I must say I do not like it. It works but it would take some more work later to check for string to send request to... somewhere else. So, I would like to do:
String[] values = new String[] {"David Pickwell", "Tico", "Jack Wilshere", "Nick Johanson"};
And after every item, a new separator will be presented.
How could I do it?
See these posts. It seems that others are also using a custom ListCellRender, so maybe that is the way to go. You only need to write that rendered once, though. So if you have written it in the past just parameterize the class and reuse it. I usually found it necessary to build a library of utils when using Swing, or any other GUI toolkit for that matter.
Java List with line separation Adding JSeparator to a DefaultListModel