有没有办法在不显式编辑方法代码的情况下改变方法中的某些内容?

Is there a way to shift something in a method without explicitly editing the method's code?

例如,我有一个 class,我在其中编写了一个创建 Polyline 对象的方法。请注意我如何使用 solution.setTranslateY(315),这会在我的 javafx window.

中向下移动多段线
public Polyline getSolution()
{
    Polyline solution = new Polyline();
    solution.setStrokeWidth(3);

    for (int i = 0; i < coordinates; i = i + 2)
        solution.getPoints().addAll(puzzle[i], puzzle[i + 1]);      

    solution.setTranslateY(315);

    //translates this solution farther down the display window

    return solution;
}    

如您所见,我在一个创建的对象上实现了这个 "getSolution()" 方法,方法是将它放在一个组中,然后将该组添加到我的程序场景中。

 public void start(Stage primaryStage) throws FileNotFoundException
 {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the name of the input file: ");
    String fileName = input.nextLine();                        
    ConnectTheDotsPuzzle heart = new ConnectTheDotsPuzzle(fileName);
    // When the user inputs the file, it gets sent to the constructor

    Line blueLine = new Line(0, 300, 500, 300); 
    //line between puzzle and solution
    blueLine.setStroke(Color.BLUE);
    blueLine.setStrokeWidth(3);

    Text solutionText = new Text(20, 335, "Solution:");
    solutionText.setFont(Font.font("Times", FontWeight.BOLD, 24));

    Group group = new Group(heart.getPuzzle(), heart.getSolution(),
            blueLine, solutionText);
    // grouping everything together to put in the scene

    Scene scene = new Scene(group, 500, 
            300);                                    
    primaryStage.setTitle("Connect the Dots");
    primaryStage.setScene(scene);
    primaryStage.show();        
    primaryStage.setOnCloseRequest(e -> System.exit(0));
 }

我的问题是:有没有办法让我不必在我创建的初始方法中转换我的 Polyline 对象?如何在我的启动方法中将其向下移动?如果我想创建这个的多个对象并且不总是希望它向下 315,我想知道我如何能够在我的开始方法中更改它而不是让它在我的方法中不断变化。

使自定义更容易的一种方法是将降档作为 getSolution() 方法的参数。或者,在组声明上方,您可以说

Polyline solution = heart.getSolution();
solution.setTranslateY(315);

然后在组声明中将 getSolution() 替换为解决方案。

建议的方法

一般来说,如果你想在你的场景中自动布局节点,那么你可以使用 layout pane, rather than an unmanaged parent node such as a Group

例如,要在垂直方向添加一堆折线心形解决方案,您可以使用 VBox:

VBox solutionsView = new VBox(10);
for (int i = 0; i < 10; i++) {
    solutionsView.getChildren().add(heart.getSolution())
}

除了翻译与布局

translateX/Y 通常用于调整动画属性以临时移动事物(例如通过 TranslateTransition). Instead of using translateX/Y properties for laying out your nodes, use layoutX/Y 属性,这些属性专门用于该目的。另请注意,在内部,布局窗格将自动更新其子节点的 layoutX/Y 值作为布局窗格布局传递的一部分(因此当您使用适当的布局窗格时无需显式设置这些值)。