2

JCheckBox 组件可以添加到 JComboBoxes 中吗?如果是这样,怎么做?

4

2 回答 2

3

有一些方法可以将 JCheckBoxes 转换为 JComboBoxes,但它不像在 JTable 中使用它们那么简单,因为 JComboBoxes 不使用单元格编辑器,只使用渲染器。让我们看看我是否可以在谷歌上重新找到这个......

请在此处检查:JComboCheckBox
和此处:组合框中的复选框

于 2011-02-06T07:14:46.660 回答
1
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CheckCombo implements ActionListener
{
    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));
    }

    private JPanel getContent()
    {
        String[] ids = { "north", "west", "south", "east" };
        Boolean[] values =
        {
            Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE
        };
        CheckComboStore[] stores = new CheckComboStore[ids.length];
        for(int j = 0; j < ids.length; j++)
            stores[j] = new CheckComboStore(ids[j], values[j]);
        JComboBox combo = new JComboBox(stores);
        combo.setRenderer(new CheckComboRenderer());
        combo.addActionListener(this);
        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 CheckCombo().getContent());
        f.setSize(300,160);
        f.setLocation(200,200);
        f.setVisible(true);
    }
}

/** adapted from comment section of ListCellRenderer api */
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.id);
        checkBox.setSelected(((Boolean)store.state).booleanValue());
        checkBox.setBackground(isSelected ? Color.red : Color.white);
        checkBox.setForeground(isSelected ? Color.white : Color.black);
        return checkBox;
    }
}

class CheckComboStore
{
    String id;
    Boolean state;

    public CheckComboStore(String id, Boolean state)
    {
        this.id = id;
        this.state = state;
    }
}
于 2011-02-06T07:17:23.500 回答