2013-12-14 56 views
0

突出當JComboBox剛剛製成,並將所選擇的項目的所有的背景只是正常和白色:
(忽略文本後的巨大間距)刪除的JComboBox

before

當然後我打開列表並將光標懸停在某個項目上,該項目突出顯示,全部正常,沒有任何問題。

但現在的問題是,突出保持一旦我點擊了一個項目:

after

所以我的問題是:
我怎樣才能使高亮消失?
最好不要與來自社區的軟件包或超載或其他任何困難。

如果我是正確的,它必須在組合框的動作監聽器的'根'?
所以:

public void actionPerformed(ActionEvent e) 
{ 
    if(e.getSource() == comboBox) 
    { 
     // code to delete the highlighting 
    } 
} 
+1

您可能只想嘗試不同的[外觀和感覺](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html)。 – jaco0646

+1

*「我怎樣才能使突出顯示消失?」*我(作爲假設用戶)如何知道何時該組合。有重點?這聽起來像是另一個「無法使用的GUI」。 :( –

+0

@AndrewThompson不,不,我只想要突出顯示一旦選擇了該項目,而不是當你被選中時(所以當在下拉菜單中懸停在項目上時) –

回答

0

爲了類似的問題使人們更容易,這裏是我寫的渲染代碼:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

class ComboBoxRenderer extends JLabel implements ListCellRenderer 
{ 
    private boolean colorSet; 
    private Color selectionBackgroundColor; 

    public ComboBoxRenderer() 
    { 
     setOpaque(true); 
     setHorizontalAlignment(LEFT); 
     setVerticalAlignment(CENTER); 
     colorSet = false; 
     selectionBackgroundColor = Color.red; // Have to set a color, else a compiler error will occur 
    } 

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) 
    { 
     // Check if color is set (only runs the first time) 
     if(!colorSet) 
     { 
      // Set the list' background color to original selection background of the list 
      selectionBackgroundColor = list.getSelectionBackground(); 
      // Do this only one time since the color will change later 
      colorSet = true; 
     } 

     // Set the list' background color to white (white will show once selection is made) 
     list.setSelectionBackground(Color.white); 

     // Check which item is selected 
     if(isSelected) 
     { 
      // Set background color of the item your cursor is hovering over to the original background color 
      setBackground(selectionBackgroundColor); 
     } 
     else 
     { 
      // Set background color of all other items to white 
      setBackground(Color.white); 
     } 

     // Do nothing about the text and font to be displayed 
     setText((String)value); 
     setFont(list.getFont()); 

     return this; 
    } 
} 

編輯:上面的代碼似乎並沒有爲正確,代碼更新工作,應該工作現在一切都好了

3

高亮顯示是通過組合框的默認渲染完成。

有關提供自定義渲染器的示例,請參閱Swing教程Providing Custom Renderers中的部分。您只需要一個不會根據所選值改變背景/前景的渲染器。

+0

這個解決方案真的很有幫助,一開始看起來真的很複雜(我是一個真正的新手),但最終似乎很容易 –