简体   繁体   English

从Java SWT中的事件处理程序访问窗口小部件

[英]Access a widget from an event handler in Java SWT

I'm trying to design a small Java application with an UI using Java SWT: in Eclipse, I created a new Application Window and I added a button and a label. 我正在尝试使用Java SWT设计具有UI的小型Java应用程序:在Eclipse中,我创建了一个新的“应用程序窗口”,并添加了一个按钮和一个标签。 What I want is to make it so when I click the button, the label's text changes from "Not Clicked" to "Clicked". 我想要做的就是这样,当我单击按钮时,标签的文本从“未单击”更改为“已单击”。 For this, I added an event handler for the button's SelectionEvent . 为此,我为按钮的SelectionEvent添加了一个事件处理程序。

However, I found that I cannot access the label from inside the event handler, so that I can change it's text. 但是,我发现我无法从事件处理程序内部访问标签,因此可以更改其文本。

protected void createContents() {
    shell = new Shell();
    shell.setSize(450, 300);
    shell.setText("SWT Application");

    Button btnClickMe = new Button(shell, SWT.NONE);
    btnClickMe.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent arg0) {
            lblStatus.setText("Clicked"); // the compiler can't find lblStatus
        }
    });
    btnClickMe.setBounds(10, 10, 75, 25);
    btnClickMe.setText("Click Me");

    Label lblStatus = new Label(shell, SWT.NONE);
    lblStatus.setBounds(10, 47, 75, 15);
    lblStatus.setText("Not clicked.");

}

I realize this is probably a dumb question, but I've been searching for a fix to no avail. 我意识到这可能是一个愚蠢的问题,但是我一直在寻找无济于事的解决方案。 I'm quite new to using Java widgets (only worked with C# in VS until now). 我是使用Java小部件的新手(到目前为止,仅在VS中使用C#)。

You have to declare lblStatus before referencing it. 您必须在引用lblStatus之前声明它。 There is no hoisting like in JavaScript. 没有像JavaScript中那样的吊装。 Right now, your are declaring the label after the event handler. 现在,您正在事件处理程序之后声明标签。

To have access to lblStatus you should declare it as the class instance variable. 要访问lblStatus您应该将其声明为类实例变量。

public class MyClass {
    Label lblStatus;

protected void createContents() {
    shell = new Shell();
    shell.setSize(450, 300);
    shell.setText("SWT Application");

    Button btnClickMe = new Button(shell, SWT.NONE);
    btnClickMe.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent arg0) {
            lblStatus.setText("Clicked"); // the compiler is aware of lblStatus
        }
    });
    btnClickMe.setBounds(10, 10, 75, 25);
    btnClickMe.setText("Click Me");

    lblStatus = new Label(shell, SWT.NONE);
    lblStatus.setBounds(10, 47, 75, 15);
    lblStatus.setText("Not clicked.");

}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM