簡體   English   中英

如何控制SWT中工具欄項的位置?

[英]how to control on the position of toolbar Item in SWT?

我有3個ToolItem:text,item1,item2

我希望該文本項將對齊到左側,項目1和項目2將對齊到右側

例如

 text                         item1,item2

這是代碼

ToolBar treeToolBar = new ToolBar(treeComposite,SWT.NONE);

    filterText = new Text(treeToolBar, SWT.BORDER);

    ToolItem textItem = new ToolItem(treeToolBar, SWT.SEPARATOR);
    textItem.setControl(filterText);
    textItem.setWidth(filterText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);

    Item1 = new ToolItem(treeToolBar, SWT.PUSH | SWT.RIGHT);

    item2 = new ToolItem(treeToolBar, SWT.PUSH | SWT.RIGHT);

如果您只想在中間的某個位置使用item1和item2,請添加一個樣式為SWT.SEPARATOR的新項目,並設置所需的寬度以抵消這兩個項目。

如果您確實希望這兩個項目位於工具欄的右側,則必須動態計算該分隔符的大小。 基本上你從工具欄的大小中減去三個項目的大小(一個文本和兩個推送項目)。

這是一個完整的片段,文本左側對齊,右側按鈕對齊。 必須使用toolbar.pack()調用來計算項目和修剪之間使用的空間。 我們也必須考慮到這一點。

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    final Composite treeComposite = new Composite(shell, SWT.NONE);
    treeComposite.setLayout(new GridLayout());

    final ToolBar treeToolBar = new ToolBar(treeComposite, SWT.NONE);
    treeToolBar.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

    final Text filterText = new Text(treeToolBar, SWT.BORDER);

    final ToolItem textItem = new ToolItem(treeToolBar, SWT.SEPARATOR);
    textItem.setControl(filterText);
    textItem.setWidth(filterText.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);

    final ToolItem separator = new ToolItem(treeToolBar, SWT.SEPARATOR);
    separator.setWidth(0);

    final ToolItem item1 = new ToolItem(treeToolBar, SWT.PUSH | SWT.RIGHT);
    item1.setImage(display.getSystemImage(SWT.ICON_WORKING));

    final ToolItem item2 = new ToolItem(treeToolBar, SWT.PUSH | SWT.RIGHT);
    item2.setImage(display.getSystemImage(SWT.ICON_QUESTION));

    treeToolBar.pack();
    final int trimSize = treeToolBar.getSize().x - textItem.getWidth() - item1.getWidth() - item2.getWidth();

    treeToolBar.addListener(SWT.Resize, new Listener() {
        @Override
        public void handleEvent(Event event) {
            final int toolbarWidth = treeToolBar.getSize().x;
            final int itemsWidth = textItem.getWidth() + item1.getWidth() + item2.getWidth();
            final int separatorWidth = toolbarWidth - itemsWidth - trimSize;
            separator.setWidth(separatorWidth);
        }
    });

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

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM