Render icon to the right side in the JList using DefaultListCellRenderer

拜拜、爱过 提交于 2019-12-13 20:16:57

问题


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.

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;
    }

}

回答1:


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

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).

You have a couple of options:

  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.

  2. 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.




回答2:


The default component used in a renderer is a JLabel, so call JLabel.setHorizontalTextPosition(SwingConstants.WHATEVER).



来源:https://stackoverflow.com/questions/51796676/render-icon-to-the-right-side-in-the-jlist-using-defaultlistcellrenderer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!