package toolbar; import java.util.Arrays; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; public class SnippetToolbarResize { public static boolean forceLayout = false; private static boolean useAsyncRequest = false; public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setText("Toolbar with dynamic content"); ToolBar bar = new ToolBar(shell, SWT.WRAP | SWT.FLAT); shell.setLayout(new GridLayout()); bar.setBackground(display.getSystemColor(SWT.COLOR_RED)); Text text = new Text(shell, SWT.WRAP); text.setLayoutData(new GridData(GridData.FILL_BOTH)); text.setText("You can type some text here and add it to the combobox"); ToolItem item = new ToolItem(bar, 0); item.setText("Add Text"); ToolItem sep = new ToolItem(bar, SWT.SEPARATOR); Combo combo = new Combo(bar, SWT.READ_ONLY); sep.setWidth(100); sep.setControl(combo); ToolItem otheritem = new ToolItem(bar, 0); otheritem.setText("Click here"); otheritem.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { item.setText("You should really click here!"); forceLayout(bar); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); item.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { combo.add(text.getText()); int width = Arrays.stream(combo.getItems()).mapToInt(String::length).max().orElse(10) * 10; sep.setWidth(width); forceLayout(bar); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); shell.setSize(400, 400); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } private static void forceLayout(ToolBar bar) { // There are two problems here: if (forceLayout) { // 1) I don't really want to manually call *any* layout method and would assume // this is done automatic by the Toolbar(Item) if (useAsyncRequest) { // 2) calling bar.requestLayout() works , bar.requestLayout(); } else { // but calling // bar.layout(true, true); // or // bar.layout(true); // does not work bar.layout(); bar.layout(true); bar.layout(true, true); } } } }