问题
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).
回答1:
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.
回答2:
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.");
}
}
来源:https://stackoverflow.com/questions/33241905/access-a-widget-from-an-event-handler-in-java-swt