I would like to make a JComboBox that has check boxes for items i开发者_开发问答nstead 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?
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;
}
}
}
}
That's not what combo boxes are "for". Are you sure you don't want, say, a JMenu with JRadioButtonMenuItem
s?
If you do really want to proceed, then you'd use a custom renderer, as you suggested.
We were once given this same inane requirement as well. We complied with a brand new component.
It was essentially a JPanel
which had a text field and a down arrow button. It contained a JList
which used a JCheckbox
-derrived ListCellRenderer
. The JList
was packaged in a JPopupMenu
which was displayed on mouse clicks.
You can take a look at japura. It's a open source custom component based on swing.
精彩评论