我正在尝试将搜索栏添加到StyledText小部件的自定义版本中。我希望酒吧卡在右上角。我创建了一个你可以尝试的最小测试。
package test;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class WidgetTest {
protected final Display display = Display.getDefault();
protected Shell shell;
public static void main(String[] args) {
WidgetTest window = new WidgetTest();
window.open();
}
private void open() {
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
protected void createContents() {
shell = new Shell();
shell.setSize(300, 178);
shell.setLayout(new GridLayout(1, false));
new CustomText(shell, SWT.V_SCROLL | SWT.MULTI | SWT.H_SCROLL)
.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
}
private class CustomText extends StyledText {
private class CustomWidget extends Canvas {
public CustomWidget(Composite parent, int style) {
super(parent, style);
addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
e.gc.fillRectangle(e.gc.getClipping());
}
});
}
}
private CustomWidget widget;
public CustomText(Composite parent, int style) {
super(parent, style);
widget = new CustomWidget(this, SWT.NONE);
widget.setBackground(new Color(getDisplay(), 255,0,0));
}
@Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, height);
Point p = getSize();
widget.setBounds(p.x - 200 - 20, 0, 200, 25);
widget.moveAbove(CustomText.this);
}
}
}
红色框代表搜索框。创建窗口或重新调整大小时,框会转到正确的位置。但是,当您键入文本或滚动时,框会移动。
我尝试添加一个绘图侦听器并重置该框的位置。虽然它主要起作用,但它在图形上是微不足道的,并且在正确定位之前搜索框会移动一两帧。
addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent arg0) {
Point p = getSize();
widget.setBounds(p.x - 200 - 20, 0, 200, 25);
}
});
如何正确地将小部件固定到顶角?