寶慕林4294392
2021-07-09 18:18:01
DefaultListCellRenderer我的程序中有一個,它可以很好地完成所有工作,但我想知道是否可以將圖像添加到最右側(cè)JList而不是將其放在左側(cè)。是否可以在JList使用中將圖標渲染到右側(cè)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 回答

Cats萌萌
TA貢獻1805條經(jīng)驗 獲得超9個贊
希望文本在左邊緣,圖標在右邊緣
JList 的默認呈現(xiàn)器是 JLabel。JLabel 不支持文本和圖標之間的動態(tài)間隙(只有固定間隙)。
你有幾個選擇:
您可以嘗試使差距動態(tài)化。您設置標簽的文本/圖標并獲得其首選大小。你也知道 JList 的大小,你可以計算出文本和圖標之間的差距。然后調(diào)用該
setIconTextGap(...)
方法來設置間隙。在調(diào)用 super.getCellRendererComponent(...) 方法之前,您還需要將此間隙設置為 0。您還需要使用 Andrew 的建議將圖標與文本右側(cè)對齊。使用使用 JPanel 作為渲染器的自定義渲染器。然后,您將為面板使用 BorderLayout。您可以將“textLabel”添加到面板的 BorderLayout.LINESTART 和“iconLabel”到面板的 BorderLayout.LINE_END。然后在渲染代碼中

德瑪西亞99
TA貢獻1770條經(jīng)驗 獲得超3個贊
渲染器中使用的默認組件是 a JLabel
,因此調(diào)用JLabel.setHorizontalTextPosition(SwingConstants.WHATEVER)
.
添加回答
舉報
0/150
提交
取消