I am using a JList, and I’m trying to use JTextAreas (that implement ListCellRenderer) for the cells. It isn’t working. The cells simply display the ListCellRenderer.toString() instead of the actual JTextArea. Could someone help? Thanks.
DefaultListModel listModel = new DefaultListModel();
JList list = new JList(listModel);
add(list);
class ButtonListener implements ActionListener() {
public void actionPerformed(ActionEvent e){
listModel.clear();
for (String s : stringArray) {
listModel.addElement(new Listm(s));
}
}
}
class Listm extends JTextArea implements ListCellRenderer {
protected Listm(String text) {
setText(text); //Outputting the text element displays the desired String
}
public Component getListCellRendererComponent(JList list, Object object, int number, boolean bool, boolean bool2) {
setPreferredSize(new Dimension(x, y));
return this;
}
}
}
You should post compilable code only, and your code is a bit confusing. You shouldn’t pass text into the renderer’s constructor as this one constructor will be used for the single renderer that renders all items in the list (unless you want all to use the same code). You shouldn’t ignore the Object parameter that is passed into your getListCellRendererComponent method, for this is the data that the renderer item displays. For example: