【发布时间】:2021-09-02 22:51:50
【问题描述】:
我在 Internet 上找到了一个自定义 SWT-Column-Ratio 布局,它将复合/控件的子级设置为用户定义的比例。不幸的是,我找不到 Column-Ratio Layout 的实现来源,但代码如下所示:
public class ColumnRatioLayout extends Layout {
int[] percentages;
public ColumnRatioLayout(int... percentages) {
this.percentages = percentages;
}
@Override
protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
Control[] children = composite.getChildren();
int height = hHint;
int width = wHint;
int consumedPercent = 0;
for (int i = 0; i < children.length; i++) {
int percent = 0;
calculatePercentAndConsumedPercent(percent, consumedPercent, children, i);
Point childSize = children[i].computeSize(wHint == -1 ? -1 : wHint * percent / 100, hHint);
if (wHint == SWT.DEFAULT) {
width = Math.max(width, childSize.x * (100 - percent) / 100);
}
if (hHint == SWT.DEFAULT) {
height = Math.max(height, childSize.y);
}
}
return new Point(width, Math.max(height, 0));
}
protected void calculatePercentAndConsumedPercent(int percent, int consumedPercent, Control[] children, int i) {
if (i >= percentages.length) {
percent = (100 - consumedPercent) / (children.length - percentages.length);
} else {
percent = percentages[i];
consumedPercent += percent;
}
}
@Override
protected void layout(Composite composite, boolean flushCache) {
Control[] children = composite.getChildren();
Rectangle available = composite.getClientArea();
int x = available.x;
int consumedPercent = 0;
for (int i = 0; i < children.length - 1; i++) {
int percent;
if (i >= percentages.length) {
percent = (100 - consumedPercent) / (children.length - percentages.length);
} else {
percent = percentages[i];
consumedPercent += percent;
}
int w = available.width * percent / 100;
children[i].setBounds(x, available.y, w, available.height);
x += w;
}
if (children.length > 0) {
children[children.length - 1].setBounds(x, available.y,
available.width - (x - available.x), available.height);
}
}
}
我想测试这个布局。我正在编写一个 JUnit 测试来测试使用此布局时该比率是否为真。我已经这样做了,但它没有给我任何有用的输出 - 点 {0, 0}:
public class ColumnRatioLayoutTest {
private static Display _display;
private static Shell _shell;
private static Composite _comp;
@BeforeAll
public static void setUpAll() {
_display = new Display();
_shell = new Shell(_display);
_comp = new Composite(_shell, SWT.NONE);
}
@Test
public void setLayoutTest() {
int[] colRatio = {20, 80};
ColumnRatioLayout colLayout = new ColumnRatioLayout(colRatio);
_comp.setLayout(colLayout);
_comp.setSize(_comp.computeSize(SWT.DEFAULT, SWT.DEFAULT));
Composite comp1 = new Composite(_comp, SWT.NONE);
comp1.setLayout(new FillLayout());
comp1.setSize(comp1.computeSize(SWT.DEFAULT, SWT.DEFAULT));
Composite comp2 = new Composite(_comp, SWT.NONE);
comp2.setLayout(new FillLayout());
comp2.setSize(comp2.computeSize(SWT.DEFAULT, SWT.DEFAULT));
System.out.println("Comp1 size: " + _comp.getSize());
}
}
我基本上是想比较两个复合材料的大小,看到一个是另一个大小的 4 倍。这将完成我的测试。我怎么做?提前致谢。
【问题讨论】:
-
请注意,标准
org.eclipse.swt.custom.SashForm提供了一种让孩子加权(加上调整大小)的方法