我无法在JavaFX中绘制平行线

时间:2015-12-03 16:06:25

标签: javafx

我会在Panel中绘制线条,它们应平行放置。我创建了以下代码,但是当我运行这段代码时,这些代码就是一个在另一个上面。我做错了什么?

Stage stage = new Stage();
StackPane stackPane = new StackPane();
Line line1 = new Line(0, 50, 100, 50);
line1.setStroke(Color.BLUE);
Line line2 = new Line(0, 40, 100, 40);
line2.setStroke(Color.RED);
stackPane.getChildren().addAll(line1, line2);
Scene scene = new Scene(stackPane, 300, 250);
stage.setTitle("Gerasterte Karte");
stage.setScene(scene);
stage.show();

1 个答案:

答案 0 :(得分:0)

您遇到的问题与StackPane如何规定其子女有关。默认情况下,它会将每个子项放在窗格的中心。所以你的线条是相互叠加的,这不是你想要的。

有关您遇到的问题的解决方案,请参阅此问题的已接受answer

示例:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

public class Example extends Application {
  public static void main(String[] args) {
    launch(args);
  }
  @Override
  public void start(Stage stage) throws Exception {
    Pane stackPane = new Pane();
    Line line1 = new Line(0, 50, 100, 50);
    line1.setStroke(Color.BLUE);
    Line line2 = createParallelLine(0, 40, line1);
    line2.setStroke(Color.RED);
    stackPane.getChildren().addAll(line1, line2);
    Scene scene = new Scene(stackPane, 300, 250);
    stage.setTitle("Gerasterte Karte");
    stage.setScene(scene);
    stage.show();
  }

  /**
   * Returns a new line that is parallel to, and the same length as,
   * the specified source line which starts at the point specified by
   * the coordinates (x, y).
   *
   * @param x the x coordinate of the starting point of the returned line.
   * @param y the y coordinate of the starting point of the returned line.
   * @param source the line that is used to calculate the slope and distance
   *               of the new line which is to be returned.
   * @return a new line that is parallel to, and the same length as,
   * the specified source line which starts at the point specified by
   * the coordinates (x, y).
   */
  private Line createParallelLine(double x, double y, Line source) {
    double d = getLength(source);
    double m = getSlope(source);
    double r = Math.sqrt(1 + Math.pow(m, 2));
    double endX = x + d / r;
    double endY = y + ((d * m) / r);
    return new Line(x, y, endX, endY);
  }

  /**
   * Returns the slope of the specified line.
   * @param line whose slope is to be returned.
   * @return the slope of the specified line.
   */
  private double getSlope(Line line) {
    return (line.getEndY() - line.getStartY()) / (line.getEndX() - line.getStartX());
  }

  /**
   * Returns the length of the specified line.
   * @param line whose length is to be returned.
   * @return the length of the specified line.
   */
  private double getLength(Line line) {
    return Math.sqrt(
      Math.pow(line.getEndX() - line.getStartX(), 2) +
        Math.pow(line.getEndY() - line.getStartY(), 2)
    );
  }
}