复选下拉框列表又叫做:多选下拉框列表或复选下拉菜单
在swing这个GUI库中使用JComboBox和JCheckBox实现
swing库中的JComboBox默认并不支持复选框作为其项,因此需要自定义渲染器来实现这一功能
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
// 创建数据模型(包含选项及其状态)
List<OptionItem> options = new ArrayList<>();
options.add(new OptionItem("中国", false));
options.add(new OptionItem("美国", false));
options.add(new OptionItem("英国", false));
// 创建自定义的渲染器
ComboBoxRenderer renderer = new ComboBoxRenderer();
// 创建 JComboBox 并配置渲染器及数据模型
JComboBox<OptionItem> comboBox = new JComboBox<>(options.toArray(new OptionItem[0]));
comboBox.setRenderer(renderer);
// 显示在 JFrame 中
JFrame frame = new JFrame("请选择你的国籍");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(comboBox, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
// 定义选项类,包含选项文本和选中状态
static class OptionItem {
private String text;
private boolean selected;
public OptionItem(String text, boolean selected) {
this.text = text;
this.selected = selected;
}
public String getText() {
return text;
}
public boolean isSelected() {
return selected;
}
@Override
public String toString() {
return text; // 用于默认渲染,此处可忽略,因为我们使用自定义渲染器
}
}
// 自定义渲染器类
static class ComboBoxRenderer extends JPanel implements ListCellRenderer<OptionItem> {
private JCheckBox checkBox;
private JLabel label;
public ComboBoxRenderer() {
setLayout(new BorderLayout());
checkBox = new JCheckBox();
label = new JLabel();
add(checkBox, BorderLayout.WEST);
add(label, BorderLayout.CENTER);
}
@Override
public Component getListCellRendererComponent(JList<? extends OptionItem> list, OptionItem value, int index,
boolean isSelected, boolean cellHasFocus) {
checkBox.setSelected(value.isSelected());
label.setText(value.getText());
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
return this;
}
}
}
运行一下: