Giving 2 elements seperate alignments in a single hbox

匆匆过客 提交于 2020-04-19 05:39:53

问题


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.


回答1:


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

}




回答2:


When you call setAlignment() on Button or Label it according to JavaDoc:

Specifies how the text and graphic within the Labeled should be aligned when there is empty space within the Labeled.

So it's just a position of the text inside your Button or Label. But what you need is to wrap your Button or Label inside some container (lets say HBox) and make it fill all available space (HBox.setHgrow(..., Priority.ALWAYS)):

Button bt1= new Button("left");
HBox bt1Box = new HBox(bt1);
HBox.setHgrow(bt1Box, Priority.ALWAYS);

Label tst= new Label("right");

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


来源:https://stackoverflow.com/questions/43562409/giving-2-elements-seperate-alignments-in-a-single-hbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!