Moving Lines Around In JavaFX

Did you know, you can define ‘relative’ Lines in JavaFX? When you’re drawing complex visualizations, you sometimes want to have a Line that is horizontal and 10 pixels long, no matter what. No problem you say, just define its starting point as (x, y) and its end point as (x+10, y):

Line {
  startX: 40
  startY: 40
  endX: 50
  endY: 40
}

Sure, easy peasy. What if you want this Line to move around based on some variable’s value? You could alter the definition so its properties are bound:

var linePosition : Number = 40;

Line {
  startX: 40
  startY: bind linePosition
  endX: 50
  endY: bind linePosition
}

Works like a charm. However, doesn’t this start to feel like a lot of information for just a horizontal line? And what if I alo want to change its x-position? What you can do in JavaFX is actually define a horizontal line, simply define it relative to its origin:

Line {
  endX: 10
}

This makes a horizontal line of 10 pixels long. Now, if you want to move this around, instead of changing its startX, startY, endX and endY properties, use layoutX and layoutY:

Line {
  endX: 10
  layoutX: 40
  layoutY: 40

To me, this reads exactly like what it is: a horizontal line who’s origin is (40, 40). It makes it a lot easier to check whether the Line is in its correct place, if it is the right size, etc.

Same thing goes for vertical and diagonal Lines obviously:

// Vertical
Line {
  endY: 10
}

// Diagonal
Line {
  endX: 10
  endY: 10
}

Happy layouting! 🙂

–JH

Posted in JavaFX, Tips and Tricks and tagged .