本文介绍在 swt 应用中,通过监听 combo 下拉选择事件,动态生成并展示可多选的复选项(使用 table + check 样式),替代传统只读 combo,真正实现“带复选功能的动态列表”。
本文介绍在 swt 应用中,通过监听 combo 下拉选择事件,动态生成并展示可多选的复选项(使用 table + check 样式),替代传统只读 combo,真正实现“带复选功能的动态列表”。
在 Java SWT 开发中,Combo 控件虽支持下拉列表,但本质是单选且无法勾选多个项;若需求是“根据主下拉框(如类别 A/B/C)动态加载一组可多选的子项”,则必须改用支持复选的控件——最常用且轻量的方案是 Table 配合 SWT.CHECK 样式。
以下是一个完整、可直接运行的实践示例:
// 主类别下拉框Label itemLabel = new Label(shell, SWT.NONE);itemLabel.setText("类别");Combo comboitem = new Combo(shell, SWT.READ_ONLY);comboitem.setItems("A", "B", "C");// 复选列表区域(Table)Label listLabel = new Label(shell, SWT.NONE);listLabel.setText("可选项");Table table = new Table(shell, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);table.setHeaderVisible(false);table.setLinesVisible(false);// 布局设置(适配 GridLayout 父容器)GridData tableData = new GridData(SWT.FILL, SWT.TOP, true, false);tableData.heightHint = 120;tableData.widthHint = 180;table.setLayoutData(tableData);// 响应主下拉选择comboitem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String selected = comboitem.getText(); switch (selected) { case "A" -> createCheckItems(table, "AA", "AB", "AC"); case "B" -> createCheckItems(table, "BA", "BB", "BC", "BD"); case "C" -> createCheckItems(table, "CA", "CB", "CC", "CD"); default -> table.removeAll(); } }});
配套的 createCheckItems 工具方法:
private void createCheckItems(Table table, String... items) { table.removeAll(); for (String item : items) { TableItem ti = new TableItem(table, SWT.NONE); ti.setText(item); // 可选:默认全选或保留用户上次选择状态(需额外缓存逻辑) ti.setChecked(false); // 初始不勾选 }}
用 Combo 触发事件 + Table(SWT.CHECK) 动态填充,是 SWT 中实现“级联多选列表”的标准、稳定且可维护的方案。它既满足 UI 清晰性(明确区分单选主类与多选子项),又符合 SWT 原生控件设计哲学——不强行改造控件语义,而是选用语义匹配的组件组合达成目标。
立即学习“Java免费学习笔记(深入)”;