简体   繁体   中英

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

}

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

You have to declare lblStatus before referencing it. There is no hoisting like in 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.

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

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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