包含 JTextAreas 的 JList 显示 JTextAreas' toString() 而不是 JTextArea
我正在使用 JList,并且尝试对单元格使用 JTextAreas (实现 ListCellRenderer)。它不起作用。这些单元格仅显示 ListCellRenderer.toString() 而不是实际的 JTextArea。有人可以帮忙吗?谢谢。
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;
}
}
}
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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该只发布可编译的代码,并且您的代码有点混乱。您不应将文本传递到渲染器的构造函数中,因为该构造函数将用于渲染列表中所有项目的单个渲染器(除非您希望所有项目都使用相同的代码)。您不应忽略传递到 getListCellRendererComponent 方法中的 Object 参数,因为这是渲染器项显示的数据。例如:
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:
验证您是否正在调用
setCellRenderer()
,它设置“用于绘制列表中每个单元格的委托”。Verify that you are invoking
setCellRenderer()
, which sets "the delegate that is used to paint each cell in the list."你应该使用渲染器。我现在没有代码,但它非常简单。 JList 的默认渲染器调用 toString() 并显示结果。
You should use renderer. I do not have a code right now but it is pretty simple. The default renderer of JList calls toString() and displays the result.