如何在SWT中创建一个基于另一个Comno值更改的组合?

问题描述 投票:0回答:1

我有1个CCombo或下拉菜单,其中包含"Shoes", "Shirts", "Pants"等项目类型,我希望第二个CCombo根据第一个选择的内容更改其内容。例如,如果选择Shirts,我希望第二个CCombo为"Small", "Medium", "Large",但如果选择Shoes,我希望第二个CCombo为"8", "9", "10"。对于第一个CCombo,我有以下代码块:

final CCombo combo_2 = new CCombo(composite, SWT.BORDER);
combo_2.setToolTipText("");
combo_2.setListVisible(true);
combo_2.setItems(new String[] {"Shoes","Pants","Shirt"});
combo_2.setEditable(false);
combo_2.setBounds(57, 125, 109, 21);
combo_2.setText("Type");
combo_2.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(SelectionEvent e) {
        String typex = combo_2.getText();
        System.out.println("Type: "+ typex +" selected");
    }});

只要更改了项目类型,就会监听并打印。对于第二个CCombo,我有这个代码块:

    final CCombo combo_1 = new CCombo(composite, SWT.BORDER);
combo_1.setToolTipText("");
combo_1.setListVisible(true);
combo_1.setItems(new String[] {"Small","Medium","Large"});
combo_1.setEditable(false);
combo_1.setBounds(57, 208, 109, 21);
combo_1.setText("Size");
combo_1.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(SelectionEvent e) {
        String typey = combo_1.getText();
        System.out.println("Size "+typey+" selected");
    }});

当我尝试在第二个CCombo的块中获得typex的值时,Ecipse说"typex cannot be resolved to a variable"

java swt windowbuilder
1个回答
1
投票

你在typex中定义了typeyListener,因此,它们仅在所述听众中有效。这是因为他们的scope仅限于他们在(widgetSelected())中定义的方法。

你可以做两件事:

  1. typextypey定义为您班级的字段。然后,您可以从班级中的任何非static方法访问它们。
  2. 像这样定义你的听众:

new SelectionAdapter()
{
    @Override
    public void widgetSelected(SelectionEvent e)
    {
        String typex = combo_2.getText();
        String typey = combo_1.getText();
        System.out.println(typex + " " + typey);
    }
}

顺便说一句:除非你真的需要,否则不要使用setBounds。请改用布局。这篇文章应该是有用的:

Understanding Layouts in SWT

© www.soinside.com 2019 - 2024. All rights reserved.