[英]How can i change the background color of a JList item that is not selected?
[英]How to change background color of the selected item in JList dynamically
如何動態更改在JList中選擇的項目的背景顏色?
以下內容應該有助於作為一個起點:
public class SelectedListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (isSelected) {
c.setBackground(Color.RED);
}
return c;
}
}
// During the JList initialisation...
jlist1.setCellRenderer(new SelectedListCellRenderer());
jList1.setSelectedIndex(currentLine);
jList1.setSelectionBackground(Color.red);
只需設置要在循環中着色的所有項目的選定索引並更改顏色相應!
更簡單的方法是在Eclipse中進入設計模式,在JList的屬性中,單擊具有兩個小箭頭的按鈕,中間有一個大的黃色箭頭,以打開“顯示高級屬性”。 然后向下滾動並更改其中顯示“selectionBackground”的顏色並更改其中的顏色(它可能是灰色的,但它仍然會改變)。 現在,當您運行程序時,無論您選擇什么,背景都將是該顏色。
如果我清楚地了解你,請查看javax.swing.ListCellRenderer
。 您需要重新實現它或擴展javax.swing.DefaultListCellRenderer
並自定義getListCellRendererComponent
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.