2010-08-17 97 views
5

我正在使用GridLayout嘗試製作標籤自動增長而不隱藏任何內容。這裏有一個簡單的代碼來測試:每次我按下按鈕標籤的文字變得越大,但只有當我調整水平的窗口後,我得到正確的佈局。 有沒有辦法解決這個問題,而不必調整窗口的大小? 我想我已經嘗試了所有的財產,我仍然無法得到這個工作,這讓我瘋狂!佈局問題:自動增長標籤(SWT)

這是我得到

wrong layout

這是應該的

right layout

import org.eclipse.swt.SWT; 
import org.eclipse.swt.events.SelectionAdapter; 
import org.eclipse.swt.events.SelectionEvent; 
import org.eclipse.swt.layout.GridData; 
import org.eclipse.swt.layout.GridLayout; 
import org.eclipse.swt.widgets.Button; 
import org.eclipse.swt.widgets.Display; 
import org.eclipse.swt.widgets.Label; 
import org.eclipse.swt.widgets.List; 
import org.eclipse.swt.widgets.Shell; 

public class UItest { 

    protected Shell shell; 
    private Label label; 

    public static void main(String[] args) { 
     try { 
      UItest window = new UItest(); 
      window.open(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public void open() { 
     Display display = Display.getDefault(); 
     createContents(); 
     shell.open(); 
     shell.layout(); 
     while (!shell.isDisposed()) { 
      if (!display.readAndDispatch()) { 
       display.sleep(); 
      } 
     } 
     display.dispose(); 
    } 

    protected void createContents() { 
     shell = new Shell(); 
     shell.setSize(450, 300); 
     shell.setText("SWT Application"); 
     shell.setLayout(new GridLayout(1, false)); 

     Button button = new Button(shell, SWT.NONE); 
     button.addSelectionListener(new SelectionAdapter() { 
      public void widgetSelected(SelectionEvent arg0) { 
       label.setText(label.getText() + " " + label.getText()); 
      } 
     }); 
     button.setText("New Button"); 

     label = new Label(shell, SWT.WRAP); 
     label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); 
     label.setText("New Label"); 

     List list = new List(shell, SWT.BORDER); 
     list.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); 

    } 

    protected Label getLabel() { 
     return label; 
    } 
} 

感謝您的時間。


解決這些變化:

Button button = new Button(shell, SWT.NONE); 
button.addSelectionListener(new SelectionAdapter() { 
    public void widgetSelected(SelectionEvent arg0) { 
     label.setText(label.getText() + " " + label.getText()); 
     shell.layout(); // ADDED THIS 
    } 
}); 
button.setText("New Button"); 

label = new Label(shell, SWT.WRAP); 
// SET HORIZONTAL GRAB ON LABEL (FIRST TRUE IN GridData CONSTRUCTOR) 
label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); 
label.setText("New Label"); 

回答

6

我認爲,問題在於佈局不被無效時,文本更改 - 強行將relayouting(通過調用getShell().layout(true, true))。

+0

是的!就是這樣!,非常感謝! – 2010-08-17 14:13:17

+0

我試過了,但它完全改變了Dialog ... – 2017-12-19 05:14:12