DefaultListCellRenderer我的程序中有一个,它可以很好地完成所有工作,但我想知道是否可以将图像添加到最右侧JList而不是将其放在左侧。是否可以在JList使用中将图标渲染到右侧DefaultListCellRenderer?如果是,请帮助我在以下代码中使用它。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; }}
2 回答
![?](http://img1.sycdn.imooc.com/54586431000103bb02200220-100-100.jpg)
Cats萌萌
TA贡献1805条经验 获得超9个赞
希望文本在左边缘,图标在右边缘
JList 的默认呈现器是 JLabel。JLabel 不支持文本和图标之间的动态间隙(只有固定间隙)。
你有几个选择:
您可以尝试使差距动态化。您设置标签的文本/图标并获得其首选大小。你也知道 JList 的大小,你可以计算出文本和图标之间的差距。然后调用该
setIconTextGap(...)
方法来设置间隙。在调用 super.getCellRendererComponent(...) 方法之前,您还需要将此间隙设置为 0。您还需要使用 Andrew 的建议将图标与文本右侧对齐。使用使用 JPanel 作为渲染器的自定义渲染器。然后,您将为面板使用 BorderLayout。您可以将“textLabel”添加到面板的 BorderLayout.LINESTART 和“iconLabel”到面板的 BorderLayout.LINE_END。然后在渲染代码中
![?](http://img1.sycdn.imooc.com/5458453d0001cd0102200220-100-100.jpg)
德玛西亚99
TA贡献1770条经验 获得超3个赞
渲染器中使用的默认组件是 a JLabel
,因此调用JLabel.setHorizontalTextPosition(SwingConstants.WHATEVER)
.
添加回答
举报
0/150
提交
取消