JavaFX 8 - Add a graphic to a TitledPane on the right side

前端 未结 2 480
渐次进展
渐次进展 2021-01-14 02:40

I want to add a little icon to the title of a TitledPane. Therefore I set an empty title and add a HBox containing a Label and a

2条回答
  •  情书的邮戳
    2021-01-14 03:09

    Based on the code shown by the OP on his edited question, this code addresses the fact that the titled pane is created on a listener before the stage is shown, on a custom class.

    @Override
    public void start(Stage primaryStage) {
    
        Scene scene = new Scene(new StackPane(), 300, 250);
    
        primaryStage.setScene(scene);
    
        primaryStage.setOnShown(e -> {
            CustomTitledPane customTitledPane = new CustomTitledPane("Title", new StackPane(new Label("Graphic to the Right")));
            scene.setRoot(customTitledPane);
            customTitledPane.applyCss();
            customTitledPane.layout();
    
            // title region
            Node titleRegion=customTitledPane.lookup(".title");
            // padding
            Insets padding=((StackPane)titleRegion).getPadding();
            // image width
            double graphicWidth=customTitledPane.getGraphic().getLayoutBounds().getWidth();
            // arrow
            double arrowWidth=titleRegion.lookup(".arrow-button").getLayoutBounds().getWidth();
            // text
            double labelWidth=titleRegion.lookup(".text").getLayoutBounds().getWidth();
    
            double nodesWidth = graphicWidth+padding.getLeft()+padding.getRight()+arrowWidth+labelWidth;
    
            customTitledPane.graphicTextGapProperty().bind(customTitledPane.widthProperty().subtract(nodesWidth));
        });
    
        primaryStage.show();
    
    }
    
    class CustomTitledPane extends TitledPane {
    
        public CustomTitledPane(String titleText, Node node) {
            super(titleText, node);
            setAnimated(true);
            setCollapsible(true);
            ImageView img = new ImageView(new Image(getClass().getResource("unlock24.png").toExternalForm()));
            img.setFitHeight(10d);
            img.setPreserveRatio(true);
            img.setSmooth(true);
            setGraphic(img);
            setContentDisplay(ContentDisplay.RIGHT);
        }
    }
    

提交回复
热议问题