我有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"
最佳答案
您在typex
中定义了typey
和Listener
,因此,它们仅在所说的侦听器中有效。这是因为它们的scope仅限于(widgetSelected()
)中定义的方法。
您可以做两件事:
将typex
和typey
定义为类的字段。然后,可以从您班上的任何非static
方法访问它们。
像这样定义您的监听器:
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