I am having an issue with drawing a cross with JavaFX

て烟熏妆下的殇ゞ 提交于 2019-12-05 17:43:48

It looks like the geometry is OK, but the alignment of line2 is wrong. Among the several ways to center it,

  1. Set the alignment explicitly for the relevant GridPane child node:

    pane.setHalignment(line2, HPos.CENTER);
    
  2. Add the lines to a Pane having the desired layout; StackPane, for example, defaults to Pos.CENTER:

    StackPane lines = new StackPane(line1, line2);
    pane.add(lines, 2, 2);
    

As an aside, judicious use of constants will make tinkering a little easier. For example, use a scale value to keep sizes proportional, as shown here:

private static final int N = 50;
…
Rectangle square = new Rectangle(2 * N, 2 * N);
Circle circle = new Circle(N);
Line line1 = new Line(-N, 0, N, 0);
Line line2 = new Line(0, -N, 0, N);

I do need the horizontal line to be a bit higher up on the pane. It should resemble a "Christian cross."

Using the approach suggested by @fabian, adjust the horizontal line's endpoints as desired; note the changes for a Latin cross, seen in the image below:

Line line1 = new Line(-N, 0, N, 0); // Greek
Line line1 = new Line(-N, -N/3, N, -N/3); // Latin
…
pane.add(new Group(line1, line2), 2, 2);

GridPane aligns it's children inside the cells you add them to. This results in the relative position of the Lines changing. To fix this I recommend wrapping the Lines in a parent that does not reposition it's children, e.g. Group.

The following change will result in a "christian cross"-like shape rotated by 180°.

// pane.add(line1, 2, 2);
// pane.add(line2, 2, 2);
pane.add(new Group(line1, line2), 2, 2);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!