[英]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. 但是,花了几个小时在Google上寻找解决方案后,我仍然没有答案。
I have a function createGui
which I give a String variable text
. 我有一个函数createGui
,它提供了一个String变量text
。 This function creates a GUI where the user can click on a button. 此功能创建一个GUI,用户可以在其中单击按钮。 Whenever he clicks the button, I want to modify the variable text
. 每当他单击按钮时,我都想修改变量text
。 Also I want to set the label label
to the value of text
. 我也想将label label
设置为text
的值。 Finally, I want to return the so modified variable text
. 最后,我想返回修改后的变量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;
}
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. 这是Java8。 Here's a Java 7 version: 这是Java 7版本:
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.
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.