Skyy2010 Skyy2010 - 6 months ago 39
Java Question

Java SWT create listener to change text of a label and return data

My problem is the following. I suppose it is a rather easy problem. However, after spending several hours searching for a solution on google, I still don't have an answer.

I have a function

createGui
which I give a String variable
text
. This function creates a GUI where the user can click on a button. Whenever he clicks the button, I want to modify the variable
text
. Also I want to set the label
label
to the value of
text
. Finally, I want to return the so modified variable
text
.

Can you tell me, how to achieve my goal?

public String createGui(String text)
{
Display display = new Display();
Shell shell = new Shell( display );
shell.setLayout( new GridLayout( 1, false ) );

Label label = new Label( shell, SWT.NONE );
label.setText( "abc" );

Button b = new Button( shell, SWT.CHECK );
b.setText( "check" );

b.addSelectionListener( new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
// modify text

// change label to text

}

} );

shell.pack();
shell.open();
while( !shell.isDisposed() )
{
if( !display.readAndDispatch() )
{
display.sleep();
}
}
display.dispose();

return text;
}

Baz Baz
Answer

You can't return a value from an anonymous inner class to the caller of the containing method.

You can however pass in a callback and call a method of this callback when you're done:

public void createGui(String text, Callback callback)
{
    [...]

    b.addListener(SWT.Selection, (e) -> {
        String modifiedText = // Manipulate the text
        label.setText(modifiedText);

        callback.onChange(modifiedText);
    });

    [...]
}

private static interface Callback
{
    void onChange(String newValue); 
}

public static void main(String[] args)
{
    createGui("InitialText", (s) -> {
        // Do something with the string here.
    });
}

This is Java8. Here's a Java 7 version:

public void createGui(String text, final Callback callback)
{
    [...]

    b.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event event)
        {
            String modifiedText = // Manipulate the text
            // label.setText(modifiedText);

            callback.onChange(modifiedText);
        }
    });

    [...]
}

private interface Callback
{
    void onChange(String newValue);
}

public static void main(String[] args)
{
    createGui("InitialText", new Callback() 
    {
        @Override
        void onChange(String newValue)
        {
            // Do something with the string here.
        }
    });
}
Comments