2012-10-17 48 views
8

在我的SWT應用程序中,我在SWT外殼中有特定的組件。我們如何自動調整SWT中組件的大小?

現在我怎麼能自動根據顯示窗口的大小重新調整這個組件的大小。

Display display = new Display(); 

Shell shell = new Shell(display); 
Group outerGroup,lowerGroup; 
Text text; 

public test1() { 
    GridLayout gridLayout = new GridLayout(); 
    gridLayout.numColumns=1; 
    shell.setLayout(gridLayout); 

    outerGroup = new Group(shell, SWT.NONE); 

    GridData data = new GridData(1000,400); 
    data.verticalSpan = 2; 
    outerGroup.setLayoutData(data);  

    gridLayout = new GridLayout(); 

    gridLayout.numColumns=2; 
    gridLayout.makeColumnsEqualWidth=true; 
    outerGroup.setLayout(gridLayout); 

    ... 
} 

也就是說,當我減小窗口的大小時,它內部的組件應該按照那個出現。

+0

您可以偵聽'SWT.Resize'事件並調用組件 – Alex

回答

25

聽起來很像你沒有使用佈局。

佈局的整體概念使得擔心調整不必要的大小。佈局將考慮所有組件的大小。

我會推薦閱讀Eclipse article about layouts

你的代碼可以很容易糾正。不要設置單個組件的大小,佈局將決定它們的大小。如果你想在窗口有一個預定義的大小,設置外殼的尺寸:

public static void main(String[] args) { 
    Display display = new Display(); 
    Shell shell = new Shell(display); 
    shell.setLayout(new GridLayout(1, false)); 

    Group outerGroup = new Group(shell, SWT.NONE); 

    // Tell the group to stretch in all directions 
    outerGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); 
    outerGroup.setLayout(new GridLayout(2, true)); 
    outerGroup.setText("Group"); 

    Button left = new Button(outerGroup, SWT.PUSH); 
    left.setText("Left"); 

    // Tell the button to stretch in all directions 
    left.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); 

    Button right = new Button(outerGroup, SWT.PUSH); 
    right.setText("Right"); 

    // Tell the button to stretch in all directions 
    right.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); 

    shell.setSize(1000,400); 
    shell.open(); 

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

調整前:

Before resizing

調整後:

After resizing

+0

+1上的'layout()'很棒的答案。 –

+0

@GilbertLeBlanc乾杯隊友。 – Baz

+1

對於SWT.FILL +1,謝謝@Baz – HDdeveloper