簡體   English   中英

JList中所選項目的背景色不起作用

[英]Background color to selected item in JList not working

為什么我選擇的項目背景沒有變化? 我肯定知道我按了列表項,因為System.out.println會說出我的當前選擇並顯示所選項的ID。 沒有錯誤就沒有任何作用。 為什么呢

 Object[] tablen = sqltable.toArray();
 JList list;
 list = new JList(tablen);                     
 list.addListSelectionListener(new ListSelectionListener(){
  @Override
  public void valueChanged(ListSelectionEvent e) {
   int idx = list.getSelectedIndex();
   setOpaque(true);
    if (idx != -1){
    //list.setSelectionBackground(Color.lightGray);
    // list.setSelectionForeground(Color.lightGray);
    setForeground(Color.red);
    setBackground(Color.BLUE);
    setBackground(list.getSelectionBackground());
    setForeground(list.getSelectionForeground()); 
    System.out.println("Current selection: " + tablen[idx]);
   }else{
     setForeground(Color.red);
     setBackground(Color.BLUE);
     setBackground(list.getBackground());
     setForeground(list.getForeground());
     System.out.println("Please choose a language."); 
        }
  }                     
});
   list.setCellRenderer(new ListCellRenderer() {
   @Override
   public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
     String[] val = (String[]) value;
     return new JLabel(val[0]);
    }                           
});

在您的單元格渲染器實現中請注意, JLabel默認情況下是不透明的,這很可能是列表單元格渲染器中的背景顏色未繪制的原因。 (請參閱相關

另一方面,我將看一下提供自定義渲染器 ,以獲取有關如何實現自定義單元渲染器的更好示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM