2012-03-31 22 views
1

我想基於使用SWT Widget選擇單選按鈕來顯示兩個文本框。但是,當我選擇另一個單選按鈕時,應該隱藏以前的文本框並顯示下拉菜單。我能夠使用setVisibility(true)和false來實現功能。這裏的主要問題是,當文本框沒有顯示時(在選擇第二個單選按鈕時),它們的空間正在消耗,下拉降到低於此值。我不想浪費那麼多空間,並希望佈局重疊並消耗分配給它們的公共空間,因爲兩者不能同時使用。如何根據Eclipse中的單選按鈕更改行佈局結構SWT

回答

0

我有一個關於如何完成的想法,只是因爲好奇才嘗試過。所以我創建了一個SSCCE只需99行代碼。避免奇怪行爲的基本想法是將子類Composite並將放置(dis)出現的小部件放在那裏。所以有3種必要的方法:一種用於創建第一組小部件,一種用於第二組,另一種用於擦除所有小部件。小部件操作調用layout後,更改才能生效。

package test; 

import org.eclipse.swt.SWT; 
import org.eclipse.swt.widgets.*; 
import org.eclipse.swt.layout.*; 
import org.eclipse.swt.events.*; 

public class Foo { 
    Shell shell; 
    Button button1, button2; 
    MyComposite composite; 

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

     button1 = new Button(shell, SWT.RADIO); 
     button1.setText("Button 1"); 
     button1.setSelection(true); 
     button1.addSelectionListener(new ButtonListener()); 

     button2 = new Button(shell, SWT.RADIO); 
     button2.setText("Button 2"); 

     composite = new MyComposite(); 
     composite.createTexts(); 

     shell.open(); 
     shell.pack(); 

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

    /** 
    * A custom composite for displaying either two Combos or two Texts 
    */ 
    class MyComposite extends Composite { 
     /** Combos */ 
     Combo combo1, combo2; 

     /** Texts */ 
     Text text1, text2; 

     MyComposite() { 
      super(shell, SWT.NONE); 
      setLayout(new GridLayout(2, true)); 
     } 

     /** create the combos */ 
     void createCombos() { 
      combo1 = new Combo(this, SWT.DROP_DOWN); 
      combo1.setText("foo"); 
      combo2 = new Combo(this, SWT.DROP_DOWN); 
      combo2.setText("bar"); 
     } 

     /** create the texts */ 
     void createTexts() { 
      text1 = new Text(this, SWT.SINGLE | SWT.BORDER); 
      text1.setText("foo"); 
      text2 = new Text(this, SWT.SINGLE | SWT.BORDER); 
      text2.setText("bar"); 
     } 

     /** dispose all children */ 
     void disposeAll() { 
      for(Widget w : getChildren()) { 
       w.dispose(); 
      } 
     } 
    } 

    class ButtonListener extends SelectionAdapter { 
     @Override 
     public void widgetSelected(SelectionEvent e) { 
      // erase all 
      composite.disposeAll(); 

      // re-add widgets according to radio button state 
      if(button1.getSelection()) { 
       composite.createTexts(); 
      } 
      else { 
       composite.createCombos(); 
      } 

      // re-do layout and fit the shell 
      shell.layout(); 
      shell.pack(); 
     } 
    } 

    public static void main(String[] args) { 
     new Foo(); 
    } 
} 
+0

非常感謝菲尼亞斯。我將嘗試這種方法。如果有任何問題,請讓你知道:) – 2012-04-01 01:45:47

相關問題