使用DefaultListCellRenderer将图标渲染到JList的右侧 [英] Render icon to the right side in the JList using DefaultListCellRenderer

查看:357
本文介绍了使用DefaultListCellRenderer将图标渲染到JList的右侧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序中有一个DefaultListCellRenderer,它可以很好地完成所有工作,但是我想知道是否可以在JList的最右侧添加图像,而不是将其添加到左侧.

I have a DefaultListCellRenderer in my program and it does all the work fine but I was wondering if I can add image to the far right in the JList instead of putting it to the left.

是否可以使用DefaultListCellRenderer将图标显示在JList的右侧?

Is it possible to render icon to the right side in the JList using DefaultListCellRenderer?

如果可以,请帮助我在以下代码中使用它.

And if yes help me use that in following code.

public class RCellRenderer extends DefaultListCellRenderer {

    String runm = "";

    public RCellRenderer(String runm) {
        this.runm = runm;

    }

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        ImageIcon imageIcon = new ImageIcon("images/in.png");
        setIcon(imageIcon);
        if (value.equals(runm)) {
            Color fg = Color.BLACK;
            setForeground(fg);
        }


        return c;
    }

}

推荐答案

想要在文本的左边缘和图标在右边缘

want the text to the left edge and the icon to the right edge

JList的默认渲染器是JLabel. JLabel不支持文本和图标之间的动态间隔(仅固定间隔).

The default renderer for a JList is a JLabel. A JLabel does not support a dynamic gap between the text and icon (only a fixed gap).

您有两种选择:

  1. 您可以尝试使缝隙动态化.您设置标签的文本/图标并获得其首选大小.您还知道可以将JList的大小计算为文本和图标之间的差异.然后,调用setIconTextGap(...)方法来设置间隙.您还需要在调用super.getCellRendererComponent(...)方法之前将此间隙设置为0.您还需要使用安德鲁(Andrew)的建议来将图标对准文本的右侧.

  1. You could try to make the gap dynamic. You set the text/icon of the label and get its preferred size. You also know the size of the JList to you can calculated the difference to be the gap between the text and icon. Then you invoke the setIconTextGap(...) method to set the gap. You would also need to set this gap to 0, before invoking the super.getCellRendererComponent(...) method. You would also need to use Andrew's suggestion to align the icon to the right of the text.

使用将JPanel用作渲染器的自定义渲染器.然后,您将为面板使用BorderLayout.您将在面板的BorderLayout.LINESTART中添加"textLabel",并在面板的BorderLayout.LINE_END中添加"iconLabel".然后,在渲染代码中,您可以简单地设置两个标签的文本/图标.您还需要为列表中的选定行实施突出显示代码.

Use a custom renderer that uses a JPanel as the renderer. Then you would use a BorderLayout for the panel. You would add a "textLabel" to the BorderLayout.LINESTART and an "iconLabel" to the BorderLayout.LINE_END of the panel. Then in the rendereing code you simple set the text/icon of the two labels. You would also need to implement the highlight code for the selected row of the list.

这篇关于使用DefaultListCellRenderer将图标渲染到JList的右侧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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