How to change the parent component of components using SWT?

My window should allow two different types of layouts (this is a simple example to better illustrate it), for example.

+-------------+-------------+-------------+ | Component 1 | Component 2 | Component 3 | | | | | | | | | | | | | | | | | +-------------+-------------+-------------+ 

and

 +-------------+---------------------------+ | Component 1 | Component 2 | | | | | +---------------------------+ | | Component 3 | | | | +-------------+---------------------------+ 

where the user can switch between both, for example, using the menu item.

With SWT, you need to provide a parent when creating the component. But we will need (1) to reuse the component and (2) place them in another parent element (similar to docking frameworks). How is this possible with SWT?

+6
java swt
source share
1 answer

You can simply do this by changing the parent component.

setParent() modifies the parent control if the underlying operating system supports it. You can then layout() compound so that the changes are displayed.

Say you have three controls:

  • Compound c1 containing vertical controls
  • Compound c2 containing horizontal controls
  • Shortcut lbl
  • btn button

Here is the code:

 public class ControlSwitcher { public static void main(String[] args) { Display display = new Display(); final Shell shell = new Shell(display); GridLayout gl = new GridLayout(); gl.marginWidth = gl.marginHeight = 20; shell.setLayout(gl); final Composite c1 = new Composite(shell, SWT.NONE); c1.setBackground(new Color(display, 255, 160, 160)); RowLayout layout = new RowLayout(SWT.VERTICAL); c1.setLayout(layout); final Composite c2 = new Composite(c1, SWT.NONE); c2.setBackground(new Color(display, 160, 255, 160)); c2.setLayout(new RowLayout()); final Label lbl = new Label(c2, SWT.NORMAL); lbl.setText("Hello world"); final Button btn = new Button(c2, SWT.PUSH); btn.setText("Switch"); btn.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent arg0) { Composite target; if (btn.getParent().equals(c2)) { target = c1; } else { target = c2; } boolean success = btn.setParent(target); if (success) { target.pack(); shell.pack(); } else { throw new RuntimeException("Not supported by this platform"); } } @Override public void widgetDefaultSelected(SelectionEvent arg0) { } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } display.dispose(); } } 
+7
source share

All Articles