#1825 Canvas not sizing on JVM

tactics Thu 8 Mar 2012

I was playing around with FWT and I noticed some strangeness I didn't understand.

First, in the JS implementation, I noticed GridPane and Canvas don't play nice together unless Canvas's size is explicitly set. Is it a general rule that Canvas's need to have their sizes set before being displayed? (Can we get any specifics on this topic in the docs?)

Second, I noticed after I added an explicit size to my canvas, it works correctly in Javascript, but now the SWT implementation doesn't work right! In particular, the canvas does not conform to the size I gave. The code for this is below.

using gfx
using fwt
using ulix
using dom

class Test
{
  Window window

  new make()
  {
    window = Window(null) 
    {
      content = GridPane
      {
        numCols = 2
        Label { text = "Canvas" },
        TestCanvas(),
        Label { text = "Text" },
        Text {},
      }
    }
  }

  Void main()
  {
    window.open
  }
}

class TestCanvas : Canvas
{
  new make() 
  {
    size = Size(400, 200)
  }

  override Void onPaint(Graphics g)
  {
    w := size.w
    h := size.h

    g.antialias = true

    g.brush = Gradient("0% 0%, 100% 100%, #fff, #666")
    g.fillRect(0, 0, w, h)
  }
}

andy Thu 8 Mar 2012

Size will be overridden by most panes, so its prefSize that actually matters. Canvas doesn't really have a natural prefSize - so we could probably improve things there. That comes up every now and then - I just use a ConstraintPane as a workaround :

content = GridPane
{
  numCols = 2
  Label { text = "Canvas" },
  ConstraintPane
  {
    minw=400; maxw=400
    minh=200; maxh=200
    TestCanvas(),
  },
  Label { text = "Text" },
  Text {},
}

Optionally use it in "fill" locations - like EdgePane.center.

EDIT: Or just set it on your subclass:

class TestCanvas : Canvas
{
  override Size prefSize(Hints hints := Hints.defVal) { Size(400,200) }
  override Void onPaint(Graphics g) { ... }
}

content = GridPane
{
  numCols = 2
  Label { text = "Canvas" }, TestCanvas(),
  Label { text = "Text" },   Text {},
}

tactics Thu 8 Mar 2012

Thanks Andy! I'll try prefSize.

Login or Signup to reply.