Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Check Boxes in a JComboBox

I would like to make a JComboBox that has check boxes for items instead of text. In addition, it should be possible to check multiple items and retrieve the selected items from the component. Should I be make a custom ComboBoxUI, ComboBoxEditor, ListCellRenderer, ComboPopUp, or something different entirely? Is there an existing Java control that does this?

like image 905
javacavaj Avatar asked Dec 16 '25 14:12

javacavaj


2 Answers

This was fairly easy to implement. Found it 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;
      }
    }
  }
}
like image 125
javacavaj Avatar answered Dec 19 '25 05:12

javacavaj


That's not what combo boxes are "for". Are you sure you don't want, say, a JMenu with JRadioButtonMenuItems?

If you do really want to proceed, then you'd use a custom renderer, as you suggested.

like image 23
Jonathan Feinberg Avatar answered Dec 19 '25 03:12

Jonathan Feinberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!