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

时间:2014-05-25 02:36:40

标签: java swt windowbuilder

我有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"

1 个答案:

答案 0 :(得分:1)

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

你可以做两件事:

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

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

    BTW:除非你真的需要,否则不要使用setBounds。请改用布局。这篇文章应该会有所帮助:

    Understanding Layouts in SWT