簡體   English   中英

Java SWT創建偵聽器以更改標簽的文本並返回數據

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

我的問題如下。 我想這是一個相當容易的問題。 但是,花了幾個小時在Google上尋找解決方案后,我仍然沒有答案。

我有一個函數createGui ,它提供了一個String變量text 此功能創建一個GUI,用戶可以在其中單擊按鈕。 每當他單擊按鈕時,我都想修改變量text 我也想將label label設置為text的值。 最后,我想返回修改后的變量text

你能告訴我如何實現我的目標嗎?

 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;
  }

您不能將值從匿名內部類返回到包含方法的調用者。

但是,您可以在完成后傳遞回調並調用此回調的方法:

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

這是Java8。 這是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM