How to force Java FX scene refresh?

前端 未结 2 886
太阳男子
太阳男子 2021-01-20 10:19

I have an Java FX scene with a start button and several rectangles which represent the tiles of a map. I also have drawn a sphere which represents my explorer (it has to exp

2条回答
  •  失恋的感觉
    2021-01-20 10:42

    This is because of :

    exception : Test cannot be cast to javafx.event.EventHandler
    

    Well, I have no idea how Class cast exception came up.

    Otherwise, to delay, you can use Thread.sleep().

    UPDATE:

    Its good to use AnimationTimer to create an animation, you don't need to refresh anything.

    Here, I have done a short EG to show color rect using FillTransition.

    CODE:

    import javafx.animation.FillTransition;
    import javafx.application.Application;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.StackPane;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    
    
    public class NewFXMain1 extends Application {
    private static final double boxOuterSize = 50;
    private static final double boxInnerSize = 48;
    private static final double boxCornerRadius = 20;
    private Rectangle rectangles = new Rectangle();
    
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("rect");
    
    
        Button btn = new Button();
        StackPane root = new StackPane();
    
    
        Rectangle r = new Rectangle();
        r.setFill(Color.BLUE);
        r.setX(2 * boxOuterSize);
        r.setY(0);
        r.setWidth(boxInnerSize);
        r.setHeight(boxInnerSize);
        r.setArcHeight(boxCornerRadius);
        r.setArcWidth(boxCornerRadius);
        r.setSmooth(true);
        r.localToScene(boxOuterSize, boxOuterSize);
        rectangles = r;
    
        root.getChildren().add(rectangles);
    
        btn.setText("display");
        btn.setOnAction(new EventHandler() {
    
            @Override
            public void handle(ActionEvent event) {
               FillTransition ft = new FillTransition(Duration.millis(3000), rectangles, Color.RED, Color.BLUE);
               ft.setCycleCount(4);
               ft.setAutoReverse(true);
               ft.play();
            }
        });
    
        root.getChildren().add(btn);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
      }
    }
    

提交回复
热议问题