2

JListBox Swing 组件是否有与.NET“set DisplayMember”类似的机制?

覆盖该toString()方法是不够的,因为我还希望能够在运行时更改显示成员。

我也考虑实现我自己的ListCellRenderer,但发现它不是很方便。

有没有更简单或更优雅的方法?

谢谢你的时间。

4

2 回答 2

0

您应该围绕您的业务对象创建一个覆盖 toString() 的包装类。这样您就可以保持自己的对象干净,并且可以在运行时交换包装器。

public class MyWrapper()
{
    private MyBusinessObject object;

    public String toString()
    {
        return object.getImportantString();
    }
}
于 2010-02-12T16:28:59.187 回答
0

我想出了一个基于实现自定义的令人满意的解决方案ListCellRenderer

import java.awt.Component;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

public class DynamicCellRenderer implements ListCellRenderer {
    private final ListCellRenderer listCellRenderer;
    private String displayMember;

    public DynamicCellRenderer(String displayMember) {
        this(displayMember, new DefaultListCellRenderer());
    }

    public DynamicCellRenderer(String displayMember, ListCellRenderer wrapped) {
        listCellRenderer = wrapped;
        this.displayMember = displayMember;
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        Object displayMemberValue = getDisplayMemberValue(value);
        return listCellRenderer.getListCellRendererComponent(list, displayMemberValue, index, isSelected, cellHasFocus);
    }

    private Object getDisplayMemberValue(Object value) {
        // value is the domain class
        // only works if display member is a method, TODO: fallback to field
        // displayMember is something like "getName" -> value.getName() gets called
        try {
            return value.getClass().getMethod(displayMember).invoke(value);
        } catch (Exception ex) {
            // if anything went wrong it is the programmers fault -> propagate exception
            throw new RuntimeException(ex);
        }
    }

    public String getDisplayMember() {
        return displayMember;
    }

    public void setDisplayMember(String displayMember) {
        this.displayMember = displayMember;
    }

}

在您的客户端 GUI 代码中,您可以执行以下操作:

jListBox1.setCellRenderer(new DynamicCellRenderer("getName"));
...
...
// and later at some point
((DynamicCellRenderer) jListBox1.getCellRenderer()).setDisplayMember("getEmail");
于 2010-02-12T17:52:57.930 回答