我有一个带有嵌入式表格控件的 StyledText 小部件。但是,一旦我添加了一个 MeasureItem 侦听器来调整表格单元格的大小,表格就会在我第一次滚动时出现在 StyledText 小部件的顶部,并一直保留在那里,直到我一直滚动到预期的位置。
这是一个已知的问题?我只是做错了什么吗?
代码片段:
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.PaintObjectEvent;
import org.eclipse.swt.custom.PaintObjectListener;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.GlyphMetrics;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
public class JumpingTable {
public static void main(String[] args) {
// Initialize GUI
Display display = new Display();
Shell shell = new Shell(display);
// Create editor
StyledText styledText = new StyledText(shell, SWT.V_SCROLL);
shell.setLayout(new FillLayout());
// Insert lots of text
for (int i=0; i<100; ++i) {
styledText.append("Lorem ipsum\r\n");
}
// Create table
Table table = new Table(styledText, SWT.NONE);
table.setVisible(false); // *** prevents table from IMMEDIATELY jumping
for (int i=0; i<3; ++i) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setWidth(100);
}
for (int i=0; i<3; ++i) {
TableItem row = new TableItem(table, SWT.NONE);
row.setText(new String[] {"a", "b", "c"});
}
// Place table
int tableOffset = styledText.getCharCount();
styledText.append("\uFFFC"); // Object Replacement Code
StyleRange style = new StyleRange();
style.start = tableOffset;
style.length = 1;
style.data = table;
//table.pack();
table.setSize(300, 150); // accomodate MeasureItem's sizing
Rectangle rect = table.getBounds();
int ascent = 2*rect.height/3;
int descent = rect.height - ascent;
style.metrics = new GlyphMetrics(ascent, descent, rect.width);
styledText.setStyleRange(style);
// Draw table
styledText.addPaintObjectListener(new PaintObjectListener() {
@Override
public void paintObject(PaintObjectEvent event) {
Table table = (Table) event.style.data;
table.setVisible(true);
int y = event.y + event.ascent - event.style.metrics.ascent;
table.setLocation(event.x, y);
}
});
// Adjust sizing
table.addListener(SWT.MeasureItem, new Listener() {
@Override
public void handleEvent(Event event) {
if (event.type == SWT.MeasureItem) {
event.width = 100;
event.height = 50;
}
}
});
// Display GUI
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
// Clean up
display.dispose();
}
}