1

I'm trying to create a line with a different fill and stroke color, something like this:

enter image description here

I have tried the following:

Line line = new Line(0,0,100,100);
line.setFill(Color.RED);
line.setStroke(Color.BLACK);
line.setStrokeWidth(10);

but this gives me just a black line.

Is what I'm trying to do possible with a simple Line or do I have to use another Shape? (I would prefer using a line because I have to frequently call the setStartX, setStartY, ... methods)

Aerus
  • 4,332
  • 5
  • 43
  • 62

2 Answers2

4

If you check this question, you'll see that you can only use setStroke. Also, a possible approach to generate the same styling is proposed by using a linear gradiant.

This will work (adjust stops at your convenience for more or less black width):

Line line = new Line(0,0,100,0);
line.setStrokeWidth(10);
line.setStroke(new LinearGradient(0d, -5d, 0d, 5d, false,
                CycleMethod.NO_CYCLE, new Stop(0,Color.BLACK), 
                                      new Stop(0.199,Color.BLACK),
                                      new Stop(0.2,Color.RED),
                                      new Stop(0.799,Color.RED),
                                      new Stop(0.8,Color.BLACK)));

line gradient

Note also that since the gradient is not proportional, you need to use rotation to generate not horizontal lines.

Community
  • 1
  • 1
José Pereda
  • 44,311
  • 7
  • 104
  • 132
0

The answer of José Pereda is more elegant but I couldn't get the math right to create diagonal lines so as a workaround I simply created two lines, each with a different color:

Line stroke = new Line(0, 0, 100, 100);
Line fill = new Line(0, 0, 100, 100);
stroke.setStrokeWidth(10);
fill.setStrokeWidth(8);
stroke.setStroke(Color.BLACK);
fill.setStroke(Color.RED);
pane.addAll(stroke, fill);

No math required and I can keep on using the setStartX,setStartY, ... methods of the lines although I now have double the amount of lines.

Aerus
  • 4,332
  • 5
  • 43
  • 62
  • You can just rotate the line, with `line.setRotate(45);` to rotate from its center, or `line.getTransforms().add(new Rotate(45,0,0));` to control the pivot point. – José Pereda Mar 05 '15 at 20:20