JavaFX - text with horizontal label

I am trying to achieve an effect similar to marquee - a string of long (in my case) text that moves along the horizontal axis. I managed to get it to work, but I can’t call it satisfactory.

My class is Controlleras follows:

@FXML
private Text newsFeedText;

(...)
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
    TranslateTransition transition = TranslateTransitionBuilder.create()
            .duration(new Duration(7500))
            .node(newsFeedText)
            .interpolator(Interpolator.LINEAR)
            .cycleCount(Timeline.INDEFINITE)
            .build();   

    GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    int width = gd.getDisplayMode().getWidth();

    transition.setFromX(width);
    transition.setToX(-width);
    transition.play();
}

newsFeedText tied to some source of text that is dynamically updated, so it contains a different amount of text.

My code has at least two drawbacks:

  • Transition from -widthto +width; width- monitor resolution width

, , . , newsFeedText , "" ( ).

  • Duration newsFeedText.

, fromX toX , .

?

+4
2

, , cycleCount Timeline.INDEFINITE. , , fxml wirings:

@FXML
private Text node; // text to marquee

@FXML
private Pane parentPane; // pane on which text is placed

, :

transition = TranslateTransitionBuilder.create()
        .duration(new Duration(10))
        .node(node)
        .interpolator(Interpolator.LINEAR)
        .cycleCount(1)
        .build();

transition.setOnFinished(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent actionEvent) {
        rerunAnimation();
    }
});

rerunAnimation();

rerunAnimation():

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

recalculateTransition():

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));
}
+4

, widthProperty. newsFeedText.getScene().widthProperty(), , , newsFeedText.

, ( ), ( ). , , (, ), .

, , - , newsFeedText. - Duration.seconds(newsFeedText.get Text().length()/denominator), denominator - - , (, 7500, ). .

newsFeedText, , newsFeedText.getText().length() newsFeedText.getWidth(). , , newsFeedText , . getPrefWidth(), getMinWidth() getMaxWidth().

0

Source: https://habr.com/ru/post/1536454/


All Articles