您可以創建對多邊形的引用。如果是第一次點擊,那麼多邊形將爲null
,因此請創建一個新的並將其添加到您的窗格。然後繼續添加點直到您點擊右鍵,此時您只需將多邊形設置回null
,以便下一次左鍵單擊可再次開始一個新的多邊形。
SSCCE:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;
public class DrawPolygon extends Application {
private Polygon currentPolygon ;
@Override
public void start(Stage primaryStage) {
Pane rootPane = new Pane();
rootPane.setMinSize(600, 600);
rootPane.setOnMouseClicked(e -> {
if (e.getButton() == MouseButton.PRIMARY) {
if (currentPolygon == null) {
currentPolygon = new Polygon();
currentPolygon.setStroke(Color.BLACK);
rootPane.getChildren().add(currentPolygon);
}
currentPolygon.getPoints().addAll(e.getX(), e.getY());
} else {
currentPolygon = null ;
}
});
Scene scene = new Scene(rootPane);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
您可以解決此各種各樣的想法發揮獲得不同的用戶體驗,例如
rootPane.setOnMouseClicked(e -> {
if (e.getButton() == MouseButton.PRIMARY) {
if (currentPolygon == null) {
currentPolygon = new Polygon();
currentPolygon.getPoints().addAll(e.getX(), e.getY());
currentPolygon.setStroke(Color.BLACK);
rootPane.getChildren().add(currentPolygon);
}
currentPolygon.getPoints().addAll(e.getX(), e.getY());
} else {
currentPolygon = null ;
}
});
rootPane.setOnMouseMoved(e -> {
if (currentPolygon != null) {
currentPolygon.getPoints().set(currentPolygon.getPoints().size()-2, e.getX());
currentPolygon.getPoints().set(currentPolygon.getPoints().size()-1, e.getY());
}
});
爲了澄清,每次發生事件時,您傳遞給事件處理程序(例如'onMouseClicked')的代碼都會執行*。這裏你不需要循環。 –