java – Canvas too small to display Image in SWT – Education Career Blog

I’m trying to use a Canvas to display an animated gif. I have the animation working, but the canvas is too small to see the entire image, and I cannot get it to resize.

I can’t even get it to be the right size for the first frame, so the animation/threading code is being omitted. My code looks like:

Composite comp = new Composite(parent, SWT.None);
comp.setLayout(new GridLayout(1, false));

final ImageLoader loader = new ImageLoader();

final Canvas canvas = new Canvas(comp, SWT.None);
final Image image = new Image(Display.getCurrent(), loader.data0);

canvas.addPaintListener(new PaintListener() {
  public void paintControl(PaintEvent e) {
    e.gc.drawImage(image, 0, 0);

The canvas area ends up being a tiny box of around 30×30, regardless of how big MYFILE.gif is. What the hell?

Anything I try to use to set the canvas size (setSize, setBounds, etc) does nothing.


Try using setPreferredSize. The layout manager will call setSize and/or setBounds and clobber the values you have set, but it will try to respect preferred size if it can. You can also use setMaximumSize and setMinimumSize to control how the canvas will resize if the enclosing component is resized.

EDIT: For SWT you could try this:

GridData gridData = new GridData();
gridData.widthHint = imageWidth;
gridData.heightHint = imageHeight;

I’m not an SWT expert, but the SWT documentation seems helpful.

Leave a Comment