网格布局动态定位组件

时间:2014-07-10 07:04:32

标签: java layout swt

我有一个复合材料,其gridlayout为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 个答案:

答案 0 :(得分:1)

GridLayout不会开箱即用,但它会按照父组合返回它们的顺序呈现按钮,因此您可以创建一个自定义组合,对按钮进行排序并将其添加到按钮而不是直接添加到按钮壳牌:

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方法可以提供一种将数据附加到比较器可以用来对它们进行排序的好方法。