在另一种方法中以一种方法访问 SWT 组件

Accessing a SWT component in one method inside another method

我创建了下面的方法,它使用 SWT 创建了一个简单的帮助按钮...

public void HButtonInitialise() {
    Button btnH = new Button(shell, SWT.NONE);
    btnH.setBounds(871, 35, 51, 32);
    btnH.setText("Get More Help");

    btnH.addSelectionListener(new SelectionAdapter() {

    @Override
    public void widgetSelected(SelectionEvent e) {

        // Message box to display help message.
        MessageBox help = new MessageBox(shell, SWT.ICON_QUESTION | SWT.OK);
        help.setText("This is help");

        // Open dialog and await user selection.
        help.open();
        }
    });
}

但是,我想拆分按钮的实际创建和按钮的功能来制作两个方法,如下所示...

public void HButtonInitialise() {
    Button btnH = new Button(shell, SWT.NONE);
    btnH.setBounds(871, 35, 51, 32);
    btnH.setText("Get More Help");
}

public void HButtonFunctionality() {
    btnH.addSelectionListener(new SelectionAdapter() {  
    @Override
    public void widgetSelected(SelectionEvent e) {      
        // Message box to display help message.
        MessageBox help = new MessageBox(shell, SWT.ICON_QUESTION | SWT.OK);
        help.setText("This is help");

        // Open dialog and await user selection.
        help.open();
        }
    });
}

但是,我收到一条错误消息说 btnH cannot be resolved 并尝试在 HButtonFunctionality() 方法中调用 HButtonInitialise() 但这似乎不起作用。我不确定是否有更好的方法来做到这一点。有人能帮忙吗?

您的 btnH 在 HButtonInitialise 方法中有作用域,因此无法在方法外访问它。

// Your code
public void HButtonInitialise() {
    Button btnH = new Button(shell, SWT.NONE); // Local reference
    btnH.setBounds(871, 35, 51, 32);
    btnH.setText("Get More Help");
} // btnH has no meaning outside this method

为了使其可访问,将按钮 btnH 声明为 class 中的成员变量并在 HButtonInitialise 方法中初始化

例如,

class MyClass {
    private Button btnH;

    public void HButtonInitialise() {
        btnH = new Button(shell, SWT.NONE); // You are now assigning btnH which is accessible throughout the class
        // Write Rest of the code here
    }

    public void HButtonFunctionality() {
        // You can now freely access btnH here
    }
}

确保在其他地方使用 btnH 之前先调用 HButtonInitialise(),否则会出现 NullPointerException