Java - checkboxes in JComboBox
I would like to create a JComboBox that has checkboxes for items instead of text. In addition, it should be possible to check multiple items and extract selected items from a component. Should I create custom ComboBoxUI, ComboBoxEditor, ListCellRenderer, ComboPopUp, or something else? Is there an existing Java control that does this?
source to share
It was pretty easy to implement. Found here link text
/* * The following code is adapted from Java Forums - JCheckBox in JComboBox URL: http://forum.java.sun.com/thread.jspa?forumID=257&threadID=364705 Date of Access: July 28 2005 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
import java.util.*;
public class JComboCheckBox extends JComboBox {
public JComboCheckBox() { addStuff(); }
public JComboCheckBox(JCheckBox[] items) { super(items); addStuff(); }
public JComboCheckBox(Vector items) { super(items); addStuff(); }
public JComboCheckBox(ComboBoxModel aModel) { super(aModel); addStuff(); }
private void addStuff() {
setRenderer(new ComboBoxRenderer());
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) { itemSelected(); }
});
}
private void itemSelected() {
if (getSelectedItem() instanceof JCheckBox) {
JCheckBox jcb = (JCheckBox)getSelectedItem();
jcb.setSelected(!jcb.isSelected());
}
}
class ComboBoxRenderer implements ListCellRenderer {
private JLabel defaultLabel;
public ComboBoxRenderer() { setOpaque(true); }
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
if (value instanceof Component) {
Component c = (Component)value;
if (isSelected) {
c.setBackground(list.getSelectionBackground());
c.setForeground(list.getSelectionForeground());
} else {
c.setBackground(list.getBackground());
c.setForeground(list.getForeground());
}
return c;
} else {
if (defaultLabel==null) defaultLabel = new JLabel(value.toString());
else defaultLabel.setText(value.toString());
return defaultLabel;
}
}
}
}
source to share
We once had the same essentials. We have implemented a completely new component. Essentially this JPanel
one that has a text box and a down arrow button. It contained JList
, which used is JCheckbox
attached ListCellRenderer
. JList
was packed into JPopupMenu
which was displayed on mouse clicks.
source to share