如何使用 SWT 更改组件的父级? [英] How to change parent of components with SWT?
问题描述
我的窗口应该允许两种不同的布局(这是一个简单的例子,可以更好地说明它),例如
My window should allow two different kind of layouts (it's a simple example to better illustrate it), e.g.
+-------------+-------------+-------------+
| Component 1 | Component 2 | Component 3 |
| | | |
| | | |
| | | |
| | | |
+-------------+-------------+-------------+
和
+-------------+---------------------------+
| Component 1 | Component 2 |
| | |
| +---------------------------+
| | Component 3 |
| | |
+-------------+---------------------------+
用户可以在两者之间切换的地方,例如,使用菜单项.
where the user can switch between both, e.g., using a menu item.
使用 SWT,您需要在创建组件时提供父级.但是我们需要 (1) 重用组件和 (2) 将它们放在不同的父级中(类似于对接框架).SWT 怎么可能做到这一点?
With SWT you need to provide the parent when creating a component. But we will need to (1) reuse the component and (2) place them in a different parent (similar to docking frameworks). How is this possible with SWT?
推荐答案
您只需更改组件的父级即可.
You can simply do this by changing a component's parent.
setParent()
更改控件的父级,如果底层操作系统支持它.然后您可以layout()
复合,以便显示更改.
setParent()
changes the control's parent, if the underlying operating system supports it. Then you can layout()
the composite so the changes appear.
假设您有三个控件:
- 包含垂直控件的复合
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();
}
}
这篇关于如何使用 SWT 更改组件的父级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!