I am having problems with grabbing all the elements of a ListModel, when i try to write the strings to file they output something like the following:
[Ljava.lang.String;@79b43f[Ljava.lang.String;@79b43f
So what am i doing wrong? Here is the code that is causing the grief:
for (int i = 0; i < listModel.getSize(); i++)
{
String[] temp = listModel.getElementAt(i).toString().split("-");
bw.write(temp[0]);
bw.write(temp[1]);
System.out.println(temp[0]);
}
bw is a bufferedWriter and listModel is a custom list model that I have made.. You may notice I have split the string,, this is because i want to extract two different values from each list row, I have simply done setText(text + "-" + text) in my customCellRenderer implementation in order to enable me to use the "-" char as a delim to extract the two values
public class CustomCellRenderer extends JLabel
implements ListCellRenderer
{
JLabel left, right;
}
public CustomCellRenderer()
{
setOpaque(true);
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
String leftData = ((String[])value)[0];
String rightData = ((String[])value)[1];
// simply will not function how i want it to.. GRR
leftData = String.format("%-50s", leftData);
setText(leftData + "- " + rightData);
if (isSelected)
{
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else
{
setBackground(list.getBackground());
setForeground(list.getForeground());
setBackground(list.getBackground());
setForeground(list.getForeground());
}
return this;
}
}
What you've posted isn't the
ListModel
- it's theListCellRenderer
. But this does reinforce the idea that each item in yourJList
is aString[]
- e.g. you are casting each value in theJList
to aString[]
for rendering.It appears that there is some confusion as to where the the
ListModel
is being populated. Your post/code suggests that you think it is being populated in theListCellRenderer
- this is not the case. It is only working out how to display the values already in theListModel
.So, a quick fix could be in the 'code that's giving you grief':
However, I wouldn't really encourage this, as you'll have unchecked class casts.
Instead, I would suggest you consider why you are populating the
ListModel
withString[]
in the first place? e.g. are you constructing theJList
as follows: