在一定条件下协调光标位置和颜色变化 - JavaFX

时间:2017-05-19 03:26:32

标签: java javafx

我开始学习JavaFX。我制作了一个创建形状的简单程序。

我想做基本事件驱动的执行方法,例如:

  1. 打印光标的坐标,如果它在形状内
  2. 每次光标进入形状时更改颜色,然后在形状不合时将其更改回原始颜色
  3. 以下是我所做的

    import javafx.application.Application;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Circle;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    import javafx.scene.Group;
    import javafx.scene.shape.Rectangle;
    import javafx.scene.shape.Polygon;
    
    
    public class ColouredShapes extends Application {
    
        @Override
        public void start(Stage stage) {
            int radius = 40;
            int strokeWidth = 3;
            Color strokeColor = Color.BROWN;
    
            Circle circle1 = new Circle(250, 125, radius, Color.RED);
            circle1.setStroke(strokeColor);
            circle1.setStrokeWidth(strokeWidth);
    
            Rectangle square = new Rectangle(375, 85, 80, 80);
            square.setFill(Color.BLUE);
            square.setStroke(strokeColor);
            square.setStrokeWidth(strokeWidth);
    
            Polygon polygon = new Polygon();
            polygon.getPoints().addAll(new Double[]{
                    50.0, 85.0,
                   110.0, 60.0, 125.0, 175.0});
    
            polygon.setFill(Color.YELLOWGREEN);
    
            Group root = new Group();
            root.getChildren().addAll(circle1, square, polygon);
            Scene scene = new Scene(root, 500, 250, Color.LIGHTYELLOW);
            stage.setScene(scene);
            stage.show();
    
        }
        public static void maint(String[] args){
            launch(args);
        }
    }
    

1 个答案:

答案 0 :(得分:1)

将输入,退出和移动处理程序的事件鼠标添加到形状

square.setOnMouseMoved(new EventHandler<MouseEvent>() {

  @Override
  public void handle(final MouseEvent event) {

      System.out.println(event.getScreenX());
      System.out.println(event.getScreenY());
    }
});
square.setOnMouseEntered(new EventHandler<MouseEvent>() {

  @Override
  public void handle(final MouseEvent event) {
    square.setFill(Color.GREEN);
  }
});
square.setOnMouseExited(new EventHandler<MouseEvent>() {

  @Override
  public void handle(final MouseEvent event) {
    square.setFill(null);

  }
});