Swing JList:如何显示对象中的String? [英] Swing JList: how to show String from an object?

查看:102
本文介绍了Swing JList:如何显示对象中的String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这使我感到困惑. 我在JList中添加对象,如下所示:

this confuses me. i add objects in JList , like below:

public class RequestListModel extends AbstractListModel<Request> {

private static final long serialVersionUID = 1L;
private List<Request> data = null;

public RequestListModel (List<Request> data) {
    this.data = data;
}

@Override
public int getSize() {
    return this.data.size();
}

@Override
public Request getElementAt(int index) {
    Request request = data.get(index);
    return request;
}}

private JList<Request> getList() {
    ListModel<Request> model = new RequestListModel(this.requestList);
    if(jlist_from == null) {
        jlist_from = new JList<Request>(model);
    } else {
        jlist_from.setModel(model);
    }
    return jlist_from;
}

但是当我运行程序时,它只是显示对象的地址:

but when i run the program, it just shows the object's address :

那么我将如何显示对象中的文本? 非常感谢你.

so how would i show the text from the object ? thank you very much.

推荐答案

它只是显示对象的地址

it just show the object's address

JList的默认渲染器仅调用对象的toString()方法,默认情况下是对象地址.

The default renderer for a JList simply invokes the toString() method of the object, which by default is the objects address.

您应该为JList提供一个自定义渲染器.渲染允许您访问对象并以所需的任何格式显示对象中的任何数据.阅读Swing教程中使用自定义渲染器的部分.

You should provide a custom renderer for your JList. The render allows you to access the object and display any data from the object in any format that you wish. Read the section from the Swing tutorial on Using a Custom Renderer.

一个更简单的解决方案是在您的对象中实现自定义toString()方法.尽管不建议使用这种方法,因为在调试时应使用toString()来描述对象.

A simpler solution is to implement a custom toString() method in your object. Although this approach is not recommended since the toString() should be used to describe the object when debugging.

此外,没有理由创建自定义ListModel.您可以只使用DefaultListModel来保存您的Request对象.

Also, there is no reason to create a custom ListModel. You can just use the DefaultListModel to hold your Request objects.

这篇关于Swing JList:如何显示对象中的String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆