You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java SWT中如何实现下拉选框联动动态生成复选框列表?

Java SWT实现下拉选框联动动态复选框列表

要实现你需要的联动效果,只需把原来用于展示二级选项的Combo控件替换为带复选框样式的SWT.List控件即可,以下是修正后的完整代码:

Label itemLabel = new Label(shell, SWT.NONE);
itemLabel.setText("Item");

// 一级下拉选框
Combo comboItem = new Combo(shell, SWT.NONE | SWT.READ_ONLY);
comboItem.setItems(new String[]{"A", "B", "C"}); // 对应需求中的一级选项

// 二级复选框列表,通过SWT.CHECK样式生成带复选框的列表
List checkBoxList = new List(shell, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL);

// 给一级下拉选框添加选择监听
comboItem.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(SelectionEvent e) {
        String selectedItem = comboItem.getText();
        checkBoxList.removeAll(); // 清空原有列表项
        
        // 根据选中的一级选项添加对应二级复选框项
        switch(selectedItem) {
            case "A":
                checkBoxList.setItems(new String[]{"AA", "AB", "AC"});
                break;
            case "B":
                checkBoxList.setItems(new String[]{"BA", "BB", "BC", "BD"});
                break;
            case "C":
                checkBoxList.setItems(new String[]{"CA", "CB", "CC", "CD"});
                break;
            default:
                break;
        }
    }
});

// 可选:获取选中的复选框项示例
Button getSelectedBtn = new Button(shell, SWT.PUSH);
getSelectedBtn.setText("获取选中项");
getSelectedBtn.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(SelectionEvent e) {
        String[] selectedItems = checkBoxList.getSelection();
        System.out.println("选中的选项:");
        for(String item : selectedItems) {
            System.out.println(item);
        }
    }
});

// 给控件设置布局(以GridLayout为例)
shell.setLayout(new GridLayout(2, false));
itemLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
comboItem.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
checkBoxList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
getSelectedBtn.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 2, 1));

关键说明:

  • 使用List控件并设置SWT.CHECK样式,就能生成带复选框的列表,搭配SWT.V_SCROLL可实现垂直滚动
  • 每次选中一级下拉选项时,先调用removeAll()清空旧项,再根据选中内容添加对应二级选项
  • 若要获取用户选中的复选框项,调用getSelection()方法即可返回选中的字符串数组

内容的提问来源于stack exchange,提问作者vmaya003

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 23:12:19