JavaFX-垂直手风琴

时间:2018-06-26 14:17:38

标签: javafx accordion custom-component

嗨,我有一个关于JavaFX的问题。我担心答案是剥皮的,我对此一无所知,但这已经过去了。

我想在JavaFX中进行手风琴/ TabPane转换。我将尝试在文字中解释自己,但在接下来的内容中,我包括了我要制作的图像。

因此,我想制作一个JavaFX容器,其左侧带有一个按钮,当单击该按钮时,它将在此初始容器上移动另一个相关的容器。再次按下时,顶部容器将移回左侧。我希望按钮和顶部容器可以从左向右一起移动,然后又向后移动,就像它们彼此连接在一起一样。

为清楚起见,最好像手风琴一样,在两个不同的容器之间平稳过渡。

enter image description here

1 个答案:

答案 0 :(得分:4)

将“标准”内容和滑块内容(包含按钮和滑块内容的HBox)放置在StackPane中,并使用动画以某种方式设置translateX这样,滑块即可移入和移出视图:

@Override
public void start(Stage primaryStage) {
    Button someButton = new Button("Sample content");

    StackPane stackPane = new StackPane(someButton);
    stackPane.setPrefSize(500, 500);
    stackPane.setStyle("-fx-background-color: blue;");

    Region sliderContent = new Region();
    sliderContent.setPrefWidth(200);
    sliderContent.setStyle("-fx-background-color: red; -fx-border-color: orange; -fx-border-width: 5;");

    Button expandButton = new Button(">");

    HBox slider = new HBox(sliderContent, expandButton);
    slider.setAlignment(Pos.CENTER);
    slider.setPrefWidth(Region.USE_COMPUTED_SIZE);
    slider.setMaxWidth(Region.USE_PREF_SIZE);

    // start out of view
    slider.setTranslateX(-sliderContent.getPrefWidth());
    StackPane.setAlignment(slider, Pos.CENTER_LEFT);

    // animation for moving the slider
    Timeline timeline = new Timeline(
            new KeyFrame(Duration.ZERO, new KeyValue(slider.translateXProperty(), -sliderContent.getPrefWidth())),
            new KeyFrame(Duration.millis(500), new KeyValue(slider.translateXProperty(), 0d))
    );

    expandButton.setOnAction(evt -> {
        // adjust the direction of play and start playing, if not already done
        String text = expandButton.getText();
        boolean playing = timeline.getStatus() == Animation.Status.RUNNING;
        if (">".equals(text)) {
            timeline.setRate(1);
            if (!playing) {
                timeline.playFromStart();
            }
            expandButton.setText("<");
        } else {
            timeline.setRate(-1);
            if (!playing) {
                timeline.playFrom("end");
            }
            expandButton.setText(">");
        }
    });

    stackPane.getChildren().add(slider);

    final Scene scene = new Scene(stackPane);

    primaryStage.setScene(scene);
    primaryStage.show();
}
相关问题