Java-JComboBox中的复选框

我想制作一个JComboBox,它具有用于项目而不是文本的复选框。此外,应该可以检查多个项目并从组件中检索选定的项目。我应该做一个自定义的ComboBoxUI,ComboBoxEditor,ListCellRenderer,ComboPopUp还是其他完全不同的东西?是否有一个现有的Java控件可以做到这一点?

回答:

这相当容易实现。在这里找到链接文本

/* * 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;

}

}

}

}

以上是 Java-JComboBox中的复选框 的全部内容, 来源链接: utcz.com/qa/397483.html

回到顶部