Nil Object Exception when in a method called from paint event

In the paint event of a canvas, the following code works to create a gradient background, and depending on the state of a variable (TransportButtonInvert), invert it:

Var linearBrush As New LinearGradientBrush
linearBrush.StartPoint = New Point(0, 0)
linearBrush.EndPoint = New Point(0, g.Height)

var light as color = Color.RGB(225,225,225)
var dark as color = color.RGB(175,175,175)

if TransportButtonInvert = false then
  linearBrush.GradientStops.Add(New Pair(0, dark))
  linearBrush.GradientStops.Add(New Pair(0.5, light))
  linearBrush.GradientStops.Add(New Pair(1.0, dark))
else
  linearBrush.GradientStops.Add(New Pair(0, light))
  linearBrush.GradientStops.Add(New Pair(0.5, dark))
  linearBrush.GradientStops.Add(New Pair(1.0, light))
end if

g.Brush = linearBrush
g.FillRectangle(0, 0, g.Width, g.Height)

No problems with that. But I want to put this code in a method I can call from several similar canvases without having to duplicate it.

How would I do this correctly?

I tried setting up a method to accept a Desktop Canvas as a parameter, and sending itself to that method from the paint event (which may be totally the wrong way to do this). It gets to the second to last line, where I get a Nil Object exception:

//In the paint event, instead of the code above
TransportButtonPress(me)

Then the method I’m calling:

//Public Sub TransportButtonPress(TransportButton as DesktopCanvas)

Var linearBrush As New LinearGradientBrush
linearBrush.StartPoint = New Point(0, 0)
linearBrush.EndPoint = New Point(0, TransportButton.Height)

var light as color = Color.RGB(225,225,225)
var dark as color = color.RGB(175,175,175)

if TransportButtonInvert = false then
  linearBrush.GradientStops.Add(New Pair(0, dark))
  linearBrush.GradientStops.Add(New Pair(0.5, light))
  linearBrush.GradientStops.Add(New Pair(1.0, dark))
else
  linearBrush.GradientStops.Add(New Pair(0, light))
  linearBrush.GradientStops.Add(New Pair(0.5, dark))
  linearBrush.GradientStops.Add(New Pair(1.0, light))
end if

TransportButton.Backdrop.Graphics.Brush = linearBrush //this is where I get the exception
TransportButton.Backdrop.Graphics.FillRectangle(0, 0, TransportButton.Width, TransportButton.Height)

I’m sure I’m misunderstanding something simple here. So I’m going to go get a coffee. But there must be a way to do this from a method, outside the paint event, right?

Change your method parameter to g as Graphics, and pass the Graphics context from the Paint event to the method. Revert your lines to use the g parameter for drawing. Backdrop is a Picture object that, unless set, is Nil. It does not represent the dynamically drawn content of the canvas.

1 Like

Funny, halfway to the cafe down the street something similar occurred to me, but this is better. Thanks!

1 Like