我想做这样的事情:
使用
TitledPane
,里面有 GridPane
。在每个 GridPane
中,我有两列 - 标签列和控制列。我希望顶部TitlePane
中的标签列与底部标签列具有相同的宽度。因为否则它看起来很糟糕。当然,我不能使用固定宽度(以像素为单位),因为标签文本取决于用户语言。
这是我的代码:
public class MyGridPanes extends Application {
@Override
public void start(Stage stage) {
GridPane gridPane1 = new GridPane();
gridPane1.add(new Label("One two three"), 0, 0);
gridPane1.add(new TextField(), 1, 0);
gridPane1.setHgap(20);
var titledPane1 = new TitledPane("Top", gridPane1);
titledPane1.setCollapsible(false);
GridPane gridPane2 = new GridPane();
gridPane2.setHgap(20);
gridPane2.add(new Label("Four five six seven"), 0, 0);
gridPane2.add(new TextField(), 1, 0);
var titledPane2 = new TitledPane("Bottom", gridPane2);
titledPane2.setCollapsible(false);
Scene scene = new Scene(new VBox(titledPane1, titledPane2), 400, 200);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
这是我的结果:
谁能告诉我怎么做吗?
看看这段代码中的想法是否有帮助。您基本上需要一次创建一个子视图并将每个子视图添加到主视图中。在这种情况下,我偷工减料,因为每个子视图都使用相同的节点。想法是一样的。
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
* SedJ601
*/
public class App extends Application
{
@Override
public void start(Stage stage)
{
GridPane titledPanesRoot = new GridPane();
titledPanesRoot.setHgap(5);
titledPanesRoot.setVgap(5);
titledPanesRoot.add(creatTitledPane("One"), 0, 0);
titledPanesRoot.add(creatTitledPane("Two"), 1, 0);
titledPanesRoot.add(creatTitledPane("Three"), 0, 1);
titledPanesRoot.add(creatTitledPane("Four"), 1, 1);
Button btnConfirm = new Button("Confirm");
VBox root = new VBox(titledPanesRoot, btnConfirm);
VBox.setMargin(titledPanesRoot, new Insets(5, 5, 0, 5));
VBox.setMargin(btnConfirm, new Insets(0, 5, 5, 0));
root.setSpacing(5);
root.setAlignment(Pos.CENTER_RIGHT);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public TitledPane creatTitledPane(String titlePaneName) {
Label labela = new Label("Label " + titlePaneName + "a:");
Label labelb = new Label("Label " + titlePaneName + "b:");
Label labelc = new Label("Label " + titlePaneName + "c:");
TextField textFielda = new TextField();
TextField textFieldb = new TextField();
TextField textFieldc = new TextField();
GridPane gridPane = new GridPane();
gridPane.setHgap(2);
gridPane.add(labela, 0, 0);
gridPane.add(labelb, 0, 1);
gridPane.add(labelc, 0, 2);
gridPane.add(textFielda, 1, 0);
gridPane.add(textFieldb, 1, 1);
gridPane.add(textFieldc, 1, 2);
TitledPane titledPane = new TitledPane(titlePaneName, gridPane);
return titledPane;
}
public static void main(String[] args) {
launch();
}
}