Mega365
Mega365

Reputation: 1

How to access a label 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've 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 its 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 realized, that this is probably a dumb question, but I've been searching for a fix to no avail. I'm quite new for using Java widgets (only worked with C# in VS until now).

Upvotes: 0

Views: 696

Answers (2)

Roman C
Roman C

Reputation: 1

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

}
}

Upvotes: 1

Raoul Duke
Raoul Duke

Reputation: 455

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.

Upvotes: 1

Related Questions