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

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

我创建了下面的方法,该方法使用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,并试图在HButtonInitialise()方法内调用HButtonFunctionality(),但这似乎不起作用。我不确定是否有更好的方法可以做到这一点。有人可以帮忙吗?

java swt
1个回答
0
投票

您的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声明为类内的成员变量,并在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

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