I try to print a swt TreeViewer to png file. With:

Tree tree = treeViewer.getTree();
Image image = new Image(display, tree.getSize().x, tree.getParent().getSize().y);
GC gc = new GC(image);

System.out.println(new File(pathToSave).getAbsolutePath());
tree.print(gc);

ImageLoader loader = new ImageLoader();
loader.data = new ImageData[] { image.getImageData() };
loader.save(pathToSave, SWT.IMAGE_PNG);
gc.dispose();
image.dispose();

the png contains only the visible part of the tree. The tree has a scrollbar because it contains more elements than fit on the form.

I would like to print the tree with all elements visible and without scrollbar. Any ideas?

On swing components i could use .paintall().. swt components don't seem to know that.

有帮助吗?

解决方案

First, the size of the image should have the size the tree would have without scrolls, and not the current size. For that you should use computeSize(SWT.DEFAULT, SWT.DEFAULT, true). Then you should resize the tree that size, print, and then resize it back. Since you don't want users to notice that, during this operation you should disabled draws with setRedraw(false).

Here is a full snippet that does all this:

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    Composite composite = new Composite(shell, SWT.NONE);
    composite.setLayout(new FillLayout());

    final Tree tree = new Tree(composite, SWT.NONE);
    for (int i = 0; i < 100; i++) {
        final TreeItem treeItem = new TreeItem(tree, SWT.NONE);
        treeItem.setText(String.format("item %d long                      name", i));
    }
    tree.addListener(SWT.DefaultSelection, new Listener() {
        @Override
        public void handleEvent(Event event) {
            tree.getParent().setRedraw(false);
            final Point originalSize = tree.getSize();
            final Point size = tree.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
            final Image image = new Image(display, size.x, size.y);
            final GC gc = new GC(image);

            tree.setSize(size);
            tree.print(gc);
            tree.setSize(originalSize);

            final ImageLoader loader = new ImageLoader();
            loader.data = new ImageData[]{image.getImageData()};
            final String pathToSave = "out.png";
            System.out.println(new File(pathToSave).getAbsolutePath());
            loader.save(pathToSave, SWT.IMAGE_PNG);
            gc.dispose();
            image.dispose();
            tree.getParent().setRedraw(true);
        }
    });

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

Press enter to save the file.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top