javajavafxalignmenthboxborderpane

Giving 2 elements seperate alignments in a single hbox


I am trying to get 2 elements, a button and a label, to have their own individual alignments in a single HBox in javafx. My code thus far:

Button bt1= new Button("left");
bt1.setAlignment(Pos.BASELINE_LEFT);

Label tst= new Label("right");
tst.setAlignment(Pos.BASELINE_RIGHT);

BorderPane barLayout = new BorderPane();
HBox bottomb = new HBox(20);
barLayout.setBottom(bottomb);
bottomb.getChildren().addAll(bt1, tst);

by default, the hbox shoves both elements to the left, next to each other.

The borderpane layout is right now necessary for my project, but as for right now, is there some way to force the label tst to stay on the far right side of the hbox, and bt1 to stay on the far left?

I can also do css, if -fx-stylesheet stuff works this way.


Solution

  • You need to add the left node to an AnchorPane and make that AnchorPane grow horizontally.

    import javafx.application.*;
    import javafx.scene.*;
    import javafx.scene.control.*;
    import javafx.scene.layout.*;
    import javafx.stage.*;
    
    /**
     *
     * @author Sedrick
     */
    public class JavaFXApplication33 extends Application {
    
        @Override
        public void start(Stage primaryStage)
        {
            BorderPane bp = new BorderPane();
            HBox hbox = new HBox();
            bp.setBottom(hbox);
    
            Button btnLeft = new Button("Left");
            Label lblRight = new Label("Right");
    
            AnchorPane apLeft = new AnchorPane();
            HBox.setHgrow(apLeft, Priority.ALWAYS);//Make AnchorPane apLeft grow horizontally
            AnchorPane apRight = new AnchorPane();
            hbox.getChildren().add(apLeft);
            hbox.getChildren().add(apRight);
    
            apLeft.getChildren().add(btnLeft);
            apRight.getChildren().add(lblRight);
    
            Scene scene = new Scene(bp, 300, 250);
    
            primaryStage.setTitle("Hello World!");
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args)
        {
            launch(args);
        }
    
    }
    

    enter image description here