从 Java SWT 中的事件处理程序访问小部件 [英] Access a widget from an event handler in Java SWT

查看:24
本文介绍了从 Java SWT 中的事件处理程序访问小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Java SWT 设计一个带有 UI 的小型 Java 应用程序:在 Eclipse 中,我创建了一个新的应用程序窗口,并添加了一个按钮和一个标签.我想要的是当我单击按钮时,标签的文本从未单击"更改为已单击".为此,我为按钮的 SelectionEvent 添加了一个事件处理程序.

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. 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.

但是,我发现我无法从事件处理程序内部访问标签,因此我可以更改它的文本.

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.");

}

我意识到这可能是一个愚蠢的问题,但我一直在寻找解决方法但无济于事.我对使用 Java 小部件很陌生(直到现在只在 VS 中使用 C#).

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).

推荐答案

要访问 lblStatus,您应该将其声明为类实例变量.

To have access to lblStatus you should declare it as the class instance variable.

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.");

}
}

这篇关于从 Java SWT 中的事件处理程序访问小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆