JavaFX - horizontal marquee text

后端 未结 2 1366
陌清茗
陌清茗 2020-12-16 06:54

I am trying to achieve effect similar to marquee - line of long (in my case) text which is moved in horizontal axis. I managed to get it work, but I can\'t call it satisfact

2条回答
  •  眼角桃花
    2020-12-16 07:21

    I have managed it to work, any recalculations can happen only after transition is stopped so we cannot set its cycleCount to Timeline.INDEFINITE. My requirement was that I could change text inside component so there are fxml wirings:

    @FXML
    private Text node; // text to marquee
    
    @FXML
    private Pane parentPane; // pane on which text is placed
    

    The code which works is:

    transition = TranslateTransitionBuilder.create()
            .duration(new Duration(10))
            .node(node)
            .interpolator(Interpolator.LINEAR)
            .cycleCount(1)
            .build();
    
    transition.setOnFinished(new EventHandler() {
        @Override
        public void handle(ActionEvent actionEvent) {
            rerunAnimation();
        }
    });
    
    rerunAnimation();
    

    where rerunAnimation() is:

    private void rerunAnimation() {
        transition.stop();
        // if needed set different text on "node"
        recalculateTransition();
        transition.playFromStart();
    }
    

    and recalculateTransition() is:

    private void recalculateTransition() {
        transition.setToX(node.getBoundsInLocal().getMaxX() * -1 - 100);
        transition.setFromX(parentPane.widthProperty().get() + 100);
    
        double distance = parentPane.widthProperty().get() + 2 * node.getBoundsInLocal().getMaxX();
        transition.setDuration(new Duration(distance / SPEED_FACTOR));
    }
    

提交回复
热议问题