gpt4 book ai didi

Java - JComboBox 中的复选框

转载 作者:行者123 更新时间:2023-12-02 07:52:59 31 4
gpt4 key购买 nike

我想制作一个 JComboBox,其中包含项目的复选框而不是文本。此外,应该可以检查多个项目并从组件中检索选定的项目。我应该制作自定义 ComboBoxUI、ComboBoxEditor、ListCellRenderer、ComboPopUp 还是完全不同的东西?是否有现有的 Java 控件可以执行此操作?

最佳答案

这相当容易实现。在这里找到它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;
}
}
}
}

关于Java - JComboBox 中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1573159/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com