JavaFX - 如何在窗格中打开和显示图像?

JavaFX - How do you open and display an image in a pane?

我正在尝试创建一个允许用户打开图像文件并将其显示在窗格中的应用程序。我选择了 JavaFX 来创建 GUI,但这给下面的代码带来了一些困难:

public class Controller implements Initializable 
{

  ...

  public void openFile()
  { 
    fileChooser = new FileChooser();
    file = fileChooser.showOpenDialog(stage);

    if (file != null)
    {
      // display the image in the pane
    }
  }

  ...

}

基本上,我需要 Controller class 来更新我视图中的 pane,它在 .fxml 文件中定义如下:

<Pane maxHeight="1.8" style="-fx-border-color: #000000;" GridPane.rowIndex="1"/>

事实上,我找不到这样做的方法,因为我无法引用 pane

您需要将 FXML 文件中的元素注入到控制器中,以便您可以在那里访问它。见 tutorial (the section "Add rows to the table", listings 3-14 and 3-16), or the documentation.

基本上,您需要在 FXML 文件中的定义中添加一个 fx:id="..." 属性,其值与控制器中的变量名称匹配 class:

<Pane fx:id="pane" maxHeight="1.8" style="-fx-border-color: #000000;" GridPane.rowIndex="1"/>

然后用@FXML注释控制器中的字段定义。确保变量名称与 fx:id 值匹配:

public class Controller implements Initializable 
{

  @FXML
  private Pane pane ;

  // ...    

  public void openFile()
  { 
    fileChooser = new FileChooser();
    file = fileChooser.showOpenDialog(pane.getScene().getWindow());

    if (file != null)
    {
      // display the image in the pane
      pane.getChildren().add(new ImageView(file.toURI().toURL().toExternalForm()));
    }
  }
}

在 SceneBuilder 中,您可以通过选择 Pane 来设置 fx:id,然后在右侧面板的底部 "Code" 部分下输入其值: