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?

+2


source to share


4 answers


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;
      }
    }
  }
}

      

+5


source


These are not combo boxes that are in favor. Are you sure you don't want, say, JMenu with JRadioButtonMenuItem

s?



If you really want to continue, then you will use the custom renderer as you suggested .

+1


source


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.

+1


source


You can watch japura . It is an open source custom swing based component.

0


source







All Articles