[英]How to change parent of components with SWT?
我的窗口應該允許兩種不同的布局(這是一個更好地說明它的簡單示例),例如
+-------------+-------------+-------------+
| Component 1 | Component 2 | Component 3 |
| | | |
| | | |
| | | |
| | | |
+-------------+-------------+-------------+
和
+-------------+---------------------------+
| Component 1 | Component 2 |
| | |
| +---------------------------+
| | Component 3 |
| | |
+-------------+---------------------------+
用戶可以在兩者之間切換,例如,使用菜單項。
使用SWT,您需要在創建組件時提供父級。 但我們需要(1)重用組件,(2)將它們放在不同的父組件中(類似於對接框架)。 SWT如何實現這一目標?
您可以通過更改組件的父級來執行此操作。
如果底層操作系統支持 , 則 setParent()
更改控件的父級。 然后,您可以layout()
復合,以便顯示更改。
假設您有三個控件:
c1
c2
lbl
btn
這是代碼:
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.