【问题标题】:Why is my custom ListCellRenderer ignoring my calls to setText?为什么我的自定义 ListCellRenderer 忽略了我对 setText 的调用?
【发布时间】:2014-05-30 09:45:45
【问题描述】:

我创建了一个自定义 ListCellRenderer,它扩展了 Jidesoft 的 StyledLabel。我的渲染器使用的 JList 是固定宽度,因此在我的渲染器中,我尝试根据此宽度缩短文本。我在 getListCellRendererComponent 中调用 setText,它有时会起作用。当我选择一个单元格时,文本就像我从未缩短过它一样。没有与 setText 和 text-shortening 相关的分支。

我尝试使用this somewhat-related answer 中讨论自定义渲染和单元格高度的解决方案,但它在选择时也不能始终如一地工作。

编辑:一些代码

public class CustomListCellRenderer extends StyledLabel implements ListCellRenderer {

    public Component getListCellRendererComponent(
        JList list, 
        Object value, 
        int index, 
        boolean isSelected, 
        boolean cellHasFocus)   {
    setText(shortenName(value.toString(), 150));

    return this;
}

    private String shortenName(String name, int width)  {
    if(this.getGraphics() != null)  {
        final FontMetrics fontMetrics = this.getFontMetrics(this.getFont());

        String end = name.substring(name.length()/2);
        String beginning = name.substring( 0, name.length()/2);

        int stringWidth = SwingUtilities.computeStringWidth(fontMetrics, name);

        if(stringWidth < width)
            return name;

        do  {
            end = end.substring(1);
            beginning = beginning.substring(0, beginning.length() - 1);

            stringWidth = SwingUtilities.computeStringWidth(fontMetrics, beginning + "..." + end);
        } while (stringWidth > width);
        return beginning + "..." + end;
    }
    return name;
   }
    public static void main(String[] args)  {
    JFrame frame = new JFrame();
    JList list = new JList(new String[] {
            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
            "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"});
    list.setCellRenderer(new CustomListCellRenderer());
    frame.getContentPane().add(list);
    frame.setVisible(true);
}
}

【问题讨论】:

  • 如果您不向我们展示您的任何代码,我们发现调试您的代码非常困难。
  • @Takendarkk 添加了一些代码。
  • 不知道为什么要扩展 StyledLabel。您所做的只是尝试设置文本,那么为什么不扩展默认渲染器呢?不要忘记调用super.getListCellRendererComponent(...),以便获得默认的突出显示行为。我不会硬编码字符串的宽度。宽度应基于 JList 的宽度。
  • 我需要 StyledLabel 用于稍后在项目中的样式,我在这里发布的是一个非常简化的版本。感谢您的提示。

标签: java swing jlist listcellrenderer


【解决方案1】:

ListCellRenderer 的实现中,您依赖于标签的getGraphics()。有时,getGraphics()null,这没关系,但您没有输入 if(this.getGraphics() != null) 条件并只是返回未修改的字符串。这就是为什么你会得到不一致的结果。注释掉这个条件解决了发布代码中的问题。你不应该依赖getGraphics() 它的价值是你无法控制的。

【讨论】:

  • 那么我还能如何使用 FontMetrics 呢?还是我应该放弃这种方法?
  • @tM--不确定你的意思。你得到FontMetrics 使用getFontMetrics()。只是不要以if(this.getGraphics() != null)为条件。
  • 对不起,我认为 getFontMetrics() 出于某种原因依赖于 getGraphics()。删除该条件有效 - 谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-02-22
  • 2011-12-31
  • 2013-09-30
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多