[英]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.