每次点击我的窗格时我如何添加不同的图?

时间:2017-07-03 14:53:39

标签: javafx

我需要每次点击时按此顺序添加一个正方形,一个圆形和一个矩形,所以在第一次点击我会添加正方形,第二个是圆形,第三个是矩形和第四个又是广场等等。

  r1.setOnMouseClicked((T) -> {
 if (T.getClickCount() == 1 || (T.getClickCount()%2 != 0 && T.getClickCount() % 3 != 0))
             {
                 Rectangle r = new Rectangle(T.getSceneX(), T.getSceneY(), 50, 50);
                 root.getChildren().add(r);
             }
         else if (T.getClickCount()%2 == 0 && T.getClickCount() % 3 != 0) {

             Circle c1 = new Circle(T.getSceneX(), T.getSceneY(), 50);
             root.getChildren().add(c1);

        }
          else if (T.getClickCount()%2 != 0 && T.getClickCount() % 3 == 0) {

             Rectangle r3  = new Rectangle(T.getSceneX(), T.getSceneY(), 40, 70);
             root.getChildren().add(r3); 
        }
    });

1 个答案:

答案 0 :(得分:0)

我使用上面的代码完成了这个例子:

import javafx.scene.layout.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.shape.*;
import javafx.application.Application;
import javafx.scene.paint.Color;

public class Test1 extends Application{
    private int count = 0;
    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();
        Scene scene = new Scene(root, 300, 250);
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();

        Pane canvas = new Pane();
        canvas.setStyle("-fx-background-color: black;");
        canvas.setPrefSize(350,250);
        canvas.setOnMouseClicked((t) -> {
            count ++;
            System.out.println("".format("%s %s %s", count, t.getSceneX(), t.getSceneY()));
            if (count == 1 || (count%2 != 0 && count % 3 != 0))
            {
                Rectangle r = new Rectangle(50, 50, Color.RED);
                r.relocate(t.getSceneX(),t.getSceneY());
                canvas.getChildren().add(r);
            }
            else if (count%2 == 0 && count % 3 != 0) {

                Circle c1 = new Circle(50,Color.GREEN);
                c1.relocate(t.getSceneX(), t.getSceneY());
                canvas.getChildren().add(c1);

            }
            else if (count%2 != 0 && count % 3 == 0) {

                Rectangle r3  = new Rectangle(40, 70, Color.PINK);
                r3.relocate(t.getSceneX(), t.getSceneY());
                canvas.getChildren().add(r3); 
            }
        });

        root.getChildren().addAll(canvas);
     }
     public static void main(String[] args) {
        launch(args);
     }
 }