JavaFXGridPane-如何将元素居中
我有一个JavaFXGridPane-如何将元素居中,java,user-interface,positioning,javafx-2,gridpanel,Java,User Interface,Positioning,Javafx 2,Gridpanel,我有一个网格窗格,里面有一个字母标签 这是一张图片: 代码如下: int charSpacing = 1; int charsInWidth = 28; int charsInHeight = 16; double charWidth = 15; double charHeight = 20; GridPane gp = new GridPane(); gp.setAlignment(Pos.CENTER); Label[] tmp = new Label[charsInHeight*
网格窗格
,里面有一个字母标签
这是一张图片:
代码如下:
int charSpacing = 1;
int charsInWidth = 28;
int charsInHeight = 16;
double charWidth = 15;
double charHeight = 20;
GridPane gp = new GridPane();
gp.setAlignment(Pos.CENTER);
Label[] tmp = new Label[charsInHeight*charsInWidth];
String text = "W";
int currArrPos = 0;
for(int y = 0; y < charsInHeight; y++) {
HBox hbox = new HBox(charSpacing);
for(int x = 0; x < charsInWidth; x++) {
tmp[currArrPos] = new Label(text);
tmp[currArrPos].setTextFill(Paint.valueOf("white"));
tmp[currArrPos].setMinHeight(charHeight);
tmp[currArrPos].setMinWidth(charWidth);
tmp[currArrPos].setMaxHeight(charHeight);
tmp[currArrPos].setMaxWidth(charWidth);
tmp[currArrPos].setStyle("-fx-border-color: white;");
hbox.getChildren().add(tmp[currArrPos++]);
if(x%2 == 0){
text = "I";
} else{
text = "W";
}
}
gp.add(hbox, 1, y);
}
guiDisplay.getChildren().add(gp);
有人有主意吗?谢谢 哦,那很容易。我找错地方了。添加此项将完成以下工作:
tmp[currArrPos].setAlignment(Pos.CENTER);
无论如何,谢谢。- 您可以使用这个
GridPane.setHalignment(tmp[currarpos],HPos.CENTER)代码>
设置验证(Pos.CENTER)
属性-
或者您可以为包含元素的网格窗格定义一个约束
<columnConstraints>
<ColumnConstraints halignment="CENTER" />
</columnConstraints>
例如:
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.ColumnConstraints?>
<GridPane fx:controller="app.graphics.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
<columnConstraints>
<ColumnConstraints halignment="CENTER" />
</columnConstraints>
</GridPane>
为那些想知道的人导入javafx.geometry.Pos
。还有,为什么不像Java通常所做的那样,他们不把它称为Position
?
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.ColumnConstraints?>
<GridPane fx:controller="app.graphics.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
<columnConstraints>
<ColumnConstraints halignment="CENTER" />
</columnConstraints>
</GridPane>