paolo
paolo

Reputation: 2538

How to access widgets from within listener?

I am building a GUI with SWT by using WindowBuilder for Eclipse. When you drag'n'drop widgets onto your shell in WindowBuilder, your source code gets automatically generated. However, all the widget objects are declared in the createContents function. The following is an excerpt from that function:

Button btnStartServer = new Button(shlTest, SWT.NONE);
btnStartServer.addSelectionListener(new SelectionAdapter() {
    @Override
    public void widgetSelected(SelectionEvent e) {

        // how to access serverStateDisplay right here?
        // I have access to shlTest (my Shell object), though
    }
});
btnStartServer.setText("Start Server");

Canvas serverStateDisplay = new Canvas(shlTest, SWT.NONE);

As you can see, I have a selection listener that get's triggered when I click a button. Now, how can I access the canvas? The obvious solution, simply writing serverStateDisplay.doWhatever() is not working.


I found this SO question which essentially asks the same thing. However, the only solutions were to either declare the referenced widget before the listener or to declare it as a class instance variable.

This is not satisfying for me, since I build my UI with WindowBuilder. Can't WB do this automatically for me? Because when the application grows, it will be quite uncomfortable manually changing each widget declaration.


The same goes for the main loop. With the widgets declared inside the createContents function, they are not accessible once the function terminates.

Upvotes: 0

Views: 348

Answers (1)

psuzzi
psuzzi

Reputation: 2277

Indeed, to access a widget you should either declare it a field or try to get the Widget from the selection event.

In your case, I would prefer exposing your canvas as a field.

In Window Builder, to expose a local variable as a field: select the variable, then click on the button "Convert local to field".

enter image description here

Upvotes: 1

Related Questions