自定义JCombobox默认选择背景颜色不可见

时间:2011-07-27 12:25:49

标签: swing model jcombobox java

我创建了定制的组合框,扩展了JCombobox。它在弹出列表中有复选框。当我尝试在弹出窗口中选择/选中复选框时,没有选择颜色。

我尝试在自定义渲染器中将背景设置为复选框,但它不起作用。这是我的代码,如果有任何想法请帮忙。提前谢谢。

import java.awt.*;   
import java.awt.event.*;   
import java.util.ArrayList;

import javax.swing.*;   

public class MyCombo extends JComboBox implements ActionListener  
{ 
    /**
     * Serial version uid
     */
    private static final long serialVersionUID = 1L;

    /**
     * Renderer for CheckBoxListComboBox
     */
    protected CheckComboRenderer renderer;

    /**
     * Editor for CheckBoxListComboBox
     */
    protected ComboEditor editor;

    /**
     * String Buffer that holds currently selected values
     */
    protected StringBuffer selectedValues;

    /**
     * Creates a <code>CheckBoxListComboBox</code> that contains the elements
     * in the specified arrayList.  By default no item becomes selected.
     * @param arrayList ArrayList holds data to display
     */
    public MyCombo()
    {
        renderer = new CheckComboRenderer();
        editor = new ComboEditor();
        selectedValues = new StringBuffer();
        setEditable(true);
        setModel(makeModel());

        addActionListener(this);
        setRenderer(renderer);   
        setEditor(editor);
    }

    /* (non-Javadoc)
     * @see javax.swing.JComboBox#setPopupVisible(boolean)
     */
    public void setPopupVisible(boolean v) 
    {
        //Dont hide popup on click
        //super.setPopupVisible(v);
    }

    /* (non-Javadoc)
     * @see javax.swing.JComboBox#actionPerformed(java.awt.event.ActionEvent)
     */
    public void actionPerformed(ActionEvent e)
    {
        JComboBox cb = (JComboBox)e.getSource();   
        CheckComboStore store = (CheckComboStore)cb.getSelectedItem();   
        CheckComboRenderer ccr = (CheckComboRenderer)cb.getRenderer();   
        ccr.checkBox.setSelected((store.state = !store.state));   
        JTextField tf = (JTextField) editor.getEditorComponent();

        StringBuffer buffer = new StringBuffer("");
        DefaultComboBoxModel mdl = (DefaultComboBoxModel) cb.getModel();
        for (int i = 0; i < mdl.getSize(); i++)
        {
            store = (CheckComboStore)mdl.getElementAt(i);

            if (store.getState().booleanValue())
            {
                if (buffer.length() == 0)
                    buffer.append(store.getId());
                else
                    buffer.append("; " + store.getId());
            }
        }
        tf.setText(buffer.toString());
    }

    private DefaultComboBoxModel makeModel()
    {
        DefaultComboBoxModel model = new DefaultComboBoxModel();
        model.addElement(new CheckComboStore("Item1", false));
        model.addElement(new CheckComboStore("Item2", false));
        model.addElement(new CheckComboStore("Item3", false));
        model.addElement(new CheckComboStore("Item4", false));
        model.addElement(new CheckComboStore("Item5", false));
        return model;
    }

    private JPanel getContent()   
    {   
        final JComboBox combo = new JComboBox()
        {
            public void setPopupVisible(boolean v) 
            {
                //Dont hide popup on click
                //super.setPopupVisible(v);
            }
        };
        combo.setPreferredSize(new Dimension(250,25));
        combo.setEditable(true);
        combo.setModel(makeModel());

        combo.addActionListener(this);
        combo.setRenderer(renderer);   
        combo.setEditor(editor);
        JPanel panel = new JPanel(); 
        panel.add(combo);   
        return panel;   
    }   

    public static void main(String[] args)   
    {   
        JFrame f = new JFrame();   
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
        f.getContentPane().add(new MyCombo().getContent());   
        f.setSize(300,160);   
        f.setLocation(200,200);   
        f.setVisible(true);   
    }

    class CheckComboRenderer implements ListCellRenderer   
    {   
        JCheckBox checkBox; 
        public CheckComboRenderer()   
        {   
            checkBox = new JCheckBox(); 
        }   

        public Component getListCellRendererComponent(JList list,   
                                                      Object value,   
                                                      int index,   
                                                      boolean isSelected,   
                                                      boolean cellHasFocus)   
        {
            CheckComboStore store = (CheckComboStore)value;   
            checkBox.setText(store.getId());  
            checkBox.setSelected(((Boolean)store.state).booleanValue());   
            checkBox.setBackground(isSelected ? Color.red : Color.white);   
            return checkBox;
        }   
    }

    class ComboEditor implements ComboBoxEditor 
    {   
        JTextField tf;   

        public ComboEditor() 
        {   
            tf = new JTextField(""); 
        }   

        public void addActionListener( ActionListener l ) {}   

        public void addKeyListener( KeyListener k){} 

        public Component getEditorComponent() 
        {   
            return tf;                                   
        }   

        public Object getItem() 
        {   
            return tf.getText();   
        }   

        public void removeActionListener( ActionListener l ) {}   

        public void selectAll() {}   

        public void setItem( Object o ) {}   
    }  

    class CheckComboStore   
    {   
        String id = "";   
        Boolean state = false;
        public String toString()
        {
            return id;
        }

        public CheckComboStore(String id, Boolean state)   
        {   
            this.id = id;   
            this.state = state;   
        } 

        public String getId()
        {
            return id;
        }

        public Boolean getState()
        {
            return state;
        }
    }  
}   

2 个答案:

答案 0 :(得分:3)

从DefaultCellRenderer源看

    bg = DefaultLookup.getColor(this, ui, "List.dropCellBackground");
    fg = DefaultLookup.getColor(this, ui, "List.dropCellForeground");

if (isSelected) {
    setBackground(bg == null ? list.getSelectionBackground() : bg);
    setForeground(fg == null ? list.getSelectionForeground() : fg);
}
else {
    setBackground(list.getBackground());
    setForeground(list.getForeground());
}

答案 1 :(得分:0)

在Renderer类的isSelected方法中使用标记getListCellRendererComponent来更改所选项目的颜色。

类似的东西:

if(isSelected)
   setBackground(mySelectedColor)
else
   setBackground(myUnselectedColor)

注意: - 上述代码并不完美,您需要根据需要进行更改。它只是为了演示isSelected标志的使用。