【问题标题】:Problems to align a Javafx button对齐 Javafx 按钮的问题
【发布时间】:2017-05-07 09:15:07
【问题描述】:

JavaFX 的新手在这里。我目前正在开发一个 JavaFX 项目。我设法用一个文本、一个文本字段和两个按钮创建了我的主窗口:

但是,我很难将按钮定位在我想要的位置(红色填充框)

Output example

这是我的launch 方法的一部分(仅与按钮相关的代码)。请注意,grid 是一个私有 GridPane 属性。

this.grid = new GridPane();
this.grid.setPadding(new Insets(15));
this.grid.setVgap(2);
this.grid.setHgap(2);
this.grid.setAlignment(Pos.CENTER);

Button submitButton = new Button("Submit");
submitButton.setStyle("-fx-font: 20 arial; -fx-base: #b6e7c9; -fx-background-radius: 10, 10, 10, 10;");
submitButton.setBackground(new Background(new BackgroundFill(Color.LIGHTGREEN, null, null)));

Button exitButton = new Button("Exit");

exitButton.setTextFill(Color.RED);
exitButton.setStyle("-fx-font: 20 arial; -fx-base: #dbd8d6; -fx-background-radius: 10, 10, 10, 10;");
exitButton.setBackground(new Background(new BackgroundFill(Color.RED, null, null)));

this.grid.add(submitButton, 0, 2);
this.grid.add(exitButton, 1, 2);

如何将退出按钮更靠左对齐,与提交按钮对称,即在 TextField 下方? 非常感谢您的帮助。

EDIT1: 问题(文本)位于 0,0。 TextField 位于 0,1。

EDIT2 Text 和 TextField 的代码:

    TextField answer = new TextField();
    answer.autosize();
    this.answer = answer.getText();
    this.grid.add(answer, 0, 1);

    Text question = new Text("Hi there ! Press Submit to start! Exit to quit.");
    question.setFont(Font.font("Century Gothic", FontWeight.BOLD, 22));
    question.setFill(Color.BLACK);
    this.grid.add(question, 0, 0);

【问题讨论】:

  • 您想要退出按钮就在提交旁边还是就在文本字段的末尾下方?
  • 我假设TextField 在(0,1) 中。您的退出按钮位于(1, 2),这就是它未对齐的原因。它位于单独的列中。要对齐,您可能必须将按钮包装在其他东西中,并设置提交左对齐,而退出右对齐。
  • 创建一个“vbox”,把2个按钮放进去,然后把vbox放在(0,2)的grid里面;)
  • 不要创建 VBox。那样,疯狂就在谎言中。只需让文本字段占据两个单元格,使第一个按钮对齐其单元格的左侧,第二个按钮对齐其单元格的右侧。
  • 不要使用额外的布局,例如VBox(虽然我认为你的意思是HBox???)。将文本和文本字段的列跨度设置为 2,即 grid.add(text, 0, 0, 2, 1); 和 grid.add(textField, 0, 1, 2, 1);。然后按钮应该没问题。 [Edt] 你的问题包括添加文本和文本字段的代码,这样更容易提供完整的答案。

标签: java user-interface button javafx javafx-8


【解决方案1】:

使文本和文本字段跨越两列:

TextField answer = new TextField();
answer.autosize();
this.answer = answer.getText();

// node, columnIndex, rowIndex, columnSpan, rowSpan:
this.grid.add(answer, 0, 1, 2, 1);

Text question = new Text("Hi there ! Press Submit to start! Exit to quit.");
question.setFont(Font.font("Century Gothic", FontWeight.BOLD, 22));
question.setFill(Color.BLACK);
this.grid.add(question, 0, 0, 2, 1);

然后让“退出”按钮右对齐,它应该会按照你想要的方式工作:

this.grid.add(submitButton, 0, 2);
this.grid.add(exitButton, 1, 2);
GridPane.setHalignment(exitButton, HPos.RIGHT);

【讨论】:

  • 这是正确答案,如果我有时间,我会自己发布。当您已经在使用 GridPane 时,创建额外的布局工件(如 HBox 或 VBox)绝对没有意义。这只会使维护变得更加困难。
  • 谢谢!这真的很快而且很有帮助。
  • @Marrakchino 如果回答您的问题,请将答案标记为正确
猜你喜欢
  • 2017-07-24
  • 2013-04-11
  • 1970-01-01
  • 2011-10-18
  • 2018-04-17
  • 2013-02-26
  • 2017-01-06
相关资源
最近更新 更多