Reputation:
Here is my following code:
public void start(Stage primaryStage) throws Exception {
Pane pane = new Pane();
Scene scene = new Scene(pane, 500, 500);
Line line = new Line(0, 200, 500, 200);
line.setStrokeWidth(2);
line.setStroke(Color.RED);
pane.getChildren().add(line);
primaryStage.setScene(scene);
primaryStage.show();
}
It outputs a line, but I wanna clip that line. For example: If I have a line which starts from (0, 200) and ends at (500, 200), then I want to clip it from (200, 200) to (400, 200). Is there any way I can clip the line? Any help is appreciated! Thank you.
Upvotes: 0
Views: 511
Reputation: 10650
If clipping is really what you want to do (you did not tell us your real use-case) I'd still tend to use a solution that Sedrick has already shown in his code but commented out for some reason. Every shape has a setClip
method, so why not use it?
import javafx.application.Application;
import javafx.geometry.Bounds;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class LineChartSample extends Application {
int clickCount = 0;
@Override public void start(Stage stage) {
Pane pane = new Pane();
Scene scene = new Scene(pane, 500, 500);
Line line = new Line(0, 200, 500, 200);
line.setStrokeWidth(2);
line.setStroke(Color.RED);
Bounds b = line.getBoundsInParent();
System.out.println(b);
pane.getChildren().add(line);
pane.setOnMouseClicked((event)->{
++clickCount;
double d = clickCount*20.0;
Rectangle clipRect = new Rectangle(b.getMinX() + d, b.getMinY(), b.getWidth() - 2*d, b.getHeight());
line.setClip(clipRect);
});
stage.setWidth(700);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Upvotes: 1
Reputation: 13859
I used a setEndX
inside a setOnMouseClicked
listener to demostrate this. You may need to do some math and use both setEndX
and setEndY
to get your desired outcome.
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 LineChartSample extends Application {
@Override public void start(Stage stage) {
Pane pane = new Pane();
Scene scene = new Scene(pane, 500, 500);
Line line = new Line(0, 200, 500, 200);
line.setStrokeWidth(2);
line.setStroke(Color.RED);
pane.getChildren().add(line);
// Rectangle clipRect = new Rectangle(line.getBoundsInParent().getWidth(), line.getBoundsInParent().getHeight());
// line.setClip(clipRect);
line.setOnMouseClicked((event)->{
line.setEndX(line.getBoundsInLocal().getWidth() - 100);
});
stage.setWidth(700);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Upvotes: 0