在SWT中,我尝试创建一个组合,它是由几个已经存在(实例化)的组合组成的。遗憾的是,SWT不允许这样做,因为父(在其中绘制复合)必须交给构造函数。
我已经创建了一个小示例,它将(希望)展示我试图完成的任务,以及我的问题:
复合
public class Composite {
public Composite(Composite parent, ...) {
// this composite will be drawn on parent
// ...
}
// ...
}合成复合材料
public class ComposedComposite extends Composite {
// Note that there are composed composites with more than one child
public ComposedComposite(Composite parent, Composite child) {
super(parent);
// child is used as content for some control
// ...
}
// ...
}事情变得平静的地方
// ...
// This is how I would prefer to compose things
ChildComposite child = new ChildComposite(...); // zonk parent is not available yet
ComposedComposite composed = new ComposedComposite(..., child); // again parent is not available yet
MainComposite main = new MainComposite(parent, composed); // The overall parent is set from outside
// ...本问候
--编辑增加关于这个问题的更多细节
以下是我真正想要实现的目标:
我有一个主窗口,它承载着相同的TabItems。每个TabItems都有一个布局,并表示来自模型的不同数据。现在,我已经创建了两个控件,我想在一个单独的控件(容器)中复合这些控件。容器具有以下布局。
+-------------+---------------------------+
| | B |
| | |
| A +---------------------------+
| | C |
| | |
+-------------+---------------------------+三个TabItems具有相同的布局(上面的容器)。所有三个都共享一个控件(因为在所有选项卡上都需要这个控件)。
所以我想做的至少是:
SharedComposite shared = new SharedComposite(...);
shared.registerListener(this);
SomeOtherComposite comp1 = new SomeOtherComposite(...);
comp1.registerListener(this);
// ... couple of them
// know compose the controls
Container container = new Container(...);
container.setA(shared); // instead of this setters the composites may be given in the ctor
container.setB(comp1);
container.setC(comp2);
addTabItem(container);
Container container2 = new Container(shared, comp3, comp4); // other way
addTabItem(container2);因此,使用给定的答案(setParent),我可以做类似的事情。遗憾的是,我仍然不能在多个选项卡中重用复合。但是使用SWT似乎是不可能的,所以使用setParent似乎是我所能得到的最好的。
谢谢大家的帮助!
发布于 2013-09-27 06:04:12
SWT确实有setParent,但并不是所有操作系统都支持这一点,根据http://www.eclipsezone.com/eclipse/forums/t23411.html的说法,
即使在操作系统支持的Windows上也有负面影响
(不幸的是,我不知道这些影响是什么)。然而,鉴于这一限制-类似这样的限制-应该有效:
public class ComposedComposite extends Composite {
public ComposedComposite(Composite parent, Control... children) {
super(parent, SWT.NONE);
for (Control child : children) {
child.setParent(this);
}
}
public void addChild(Control c) {
c.setParent(this);
}
}您可能还需要调用layout。
https://stackoverflow.com/questions/19033731
复制相似问题