2014-07-10 69 views
1

我有一个5列网格布局的组合,它包含 一些按钮。现在是否可以添加任何其他控件到 GridLayout的特定位置?例如,我想在第三列的第一行添加一个TextField,即代替Button3 ,并且按钮3应该下到最后一行,即按钮7之后。 GridLayout中可以使用任何类型的动态定位?动态组件网格布局定位

package zrcp; 

import org.eclipse.swt.SWT; 
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.Shell; 

    public class LayoutExample { 

    protected Shell shell; 

    /** 
    * Launch the application. 
    * 
    * @param args 
    */ 
    public static void main(String[] args) { 
     try { 
      LayoutExample window = new LayoutExample(); 
      window.open(); 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    /** 
    * Open the window. 
    */ 
    public void open() { 
     Display display = Display.getDefault(); 
     createContents(); 
     shell.open(); 
     shell.layout(); 
     while (!shell.isDisposed()) { 
      if (!display.readAndDispatch()) { 
       display.sleep(); 
      } 
     } 
    } 

    /** 
    * Create contents of the window. 
    */ 
    protected void createContents() { 
     shell = new Shell(); 
     shell.setSize(450, 300); 
     shell.setText("SWT Application"); 
     shell.setLayout(new GridLayout(5, false)); 

     Button btnNewButton = new Button(shell, SWT.NONE); 
     btnNewButton.setText("Button1"); 

     Button btnNewButton_1 = new Button(shell, SWT.NONE); 
     btnNewButton_1.setText("Button2"); 

     Button btnNewButton_2 = new Button(shell, SWT.NONE); 
     btnNewButton_2.setText("Button3"); 

     Button btnNewButton_3 = new Button(shell, SWT.NONE); 
     btnNewButton_3.setText("Button4"); 

     Button btnNewButton_4 = new Button(shell, SWT.NONE); 
     btnNewButton_4.setText("Button5"); 

     Button btnNewButton_5 = new Button(shell, SWT.NONE); 
     btnNewButton_5.setText("Button6"); 
     new Label(shell, SWT.NONE); 
     new Label(shell, SWT.NONE); 
     new Label(shell, SWT.NONE); 
     new Label(shell, SWT.NONE); 

     Button btnNewButton_6 = new Button(shell, SWT.NONE); 
     btnNewButton_6.setText("Button7"); 
     new Label(shell, SWT.NONE); 
     new Label(shell, SWT.NONE); 
     new Label(shell, SWT.NONE); 
     new Label(shell, SWT.NONE); 

    } 

} 

回答

1

网格布局是不会这样做的开箱即用,但它会呈现父复合返回它们的顺序按一下按钮,这样你就可以创建一个排序按键的自定义组合,并将它们添加到而不是直接向壳牌:

class SortedComposite extends Composite { 
    private Comparator<Control> comparator; // TODO Create this 

    public SortedComposite(Composite parent, int style) { 
     super(parent, style); 
    } 

    @Override 
    public Control[] getChildren() { 
     Control[] children = super.getChildren(); 
     Arrays.sort(children, comparator); 
     return children; 
    } 

} 

setData方法上的按钮将提供数据附加到他们的比较可以使用对它们进行排序的好方法。