我有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"
答案 0 :(得分:1)
您在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);
}
}
BTW:除非你真的需要,否则不要使用setBounds
。请改用布局。这篇文章应该会有所帮助: