2017-04-22 101 views
0

我想要获得2个元素,一个按钮和一个标签,以便在javafx中的单个HBox中拥有自己的对齐。我的代码到目前为止:在单个hbox中给出2个元素单独对齐

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

默认情况下,hbox推动两个元素左边,相邻。

现在我的项目需要使用borderpane布局,但就目前而言,是否有某种方法可以强制标签tst保留在hbox的最右侧,而bt1保留在最左侧?

我也可以做css,如果-fx-stylesheet的东西以这种方式工作。

回答

1

您需要将左节点添加到AnchorPane并使该AnchorPane水平增长。

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

0

当你根据JavaDoc的呼吁ButtonLabelsetAlignment()

指定范围内的标记文本和图形应该怎么 对齐时,有内空的空间标签。

所以它只是您的ButtonLabel中的文字位置。但是,你需要的是一些包装容器内的ButtonLabel(可以说HBox),并使其填满所有可用的空间(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);