[英]Java - Check Boxes in a JComboBox
I would like to make a JComboBox that has check boxes for items instead of text. 我想制作一个JComboBox,它有项目而不是文本的复选框。 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?
我应该自定义ComboBoxUI,ComboBoxEditor,ListCellRenderer,ComboPopUp或其他不同的东西吗? Is there an existing Java control that does this?
是否存在执行此操作的现有Java控件?
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;
}
}
}
}
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. 它本质上是一个
JPanel
,它有一个文本字段和一个向下箭头按钮。 It contained a JList
which used a JCheckbox
-derrived ListCellRenderer
. 它包含一个使用
JCheckbox
-derrived ListCellRenderer
的JList
。 The JList
was packaged in a JPopupMenu
which was displayed on mouse clicks. JList
打包在JPopupMenu
,通过鼠标点击显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.