[英]How to shift buttons in the GridPane?
我想當A和C消失時,按鈕B和D會保留在它們的位置,但取而代之的是移到中間。 我如何才能將他們轉移回原處?
fifty.setOnAction(e->{
fifty.setDisable(false);
int counter = 2;
ArrayList<String> variants = new ArrayList<>(Arrays.asList("a","b","c","d"));
variants.remove(trueAnswerIndex);
String variant;
int n = 2;
while(counter>0){
variant = variants.get(randInt(0,n));
switch(variant){
case "a":
gridButtons.getChildren().remove(a);
variants.remove("a");
break;
case "b":
gridButtons.getChildren().remove(b);
variants.remove("b");
break;
case "c":
gridButtons.getChildren().remove(c);
variants.remove("c");
break;
case "d":
gridButtons.getChildren().remove(d);
variants.remove("d");
break;
}
counter--;
n--;
}
});
只是禁用按鈕的可見性 ,而不是刪除按鈕。
fifty.setOnAction(e->{
fifty.setDisable(false);
int counter = 2;
ArrayList<String> variants = new ArrayList<>(Arrays.asList("a","b","c","d"));
variants.remove(trueAnswerIndex);
String variant;
int n = 2;
while(counter>0){
variant = variants.get(randInt(0,n));
switch(variant){
case "a":
a.setVisible(false);
variants.remove("a");
break;
case "b":
b.setVisible(false);
variants.remove("b");
break;
case "c":
c.setVisible(false);
variants.remove("c");
break;
case "d":
d.setVisible(false);
variants.remove("d");
break;
}
counter--;
n--;
}
});
您可以使用一些虛擬組件(如空的Text
節點),也可以為GridPane
手動設置RowConstraints
和ColumnConstraints
。
后者是我的首選方法。 在下面的示例中,我為前兩行和列設置了這些約束,因此即使隱藏或刪除了按鈕,其他列也不會自動調整大小。
我還將GridPane
放置在另一個Node
,因為否則它將填充整個Scene
。
public class JavaFXTest extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
GridPane pane = new GridPane();
for (int i = 0; i < 2; i++) {
RowConstraints rc = new RowConstraints();
rc.setPrefHeight(100);
ColumnConstraints cc = new ColumnConstraints();
cc.setPercentWidth(100);
pane.getRowConstraints().add(rc);
pane.getColumnConstraints().add(cc);
}
Button b1 = new Button("1");
b1.setPrefSize(100, 100);
Button b2 = new Button("2");
b2.setPrefSize(100, 100);
Button b3 = new Button("3");
b3.setPrefSize(100, 100);
Button b4 = new Button("4");
b4.setPrefSize(100, 100);
b1.setOnAction(e -> {
b2.setVisible(false);
});
b2.setOnAction(e -> {
b3.setVisible(false);
});
b3.setOnAction(e -> {
b4.setVisible(false);
});
b4.setOnAction(e -> {
b1.setVisible(false);
});
pane.add(b1, 0, 0);
pane.add(b2, 1, 0);
pane.add(b3, 0, 1);
pane.add(b4, 1, 1);
root.getChildren().add(pane);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.