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

时间:2015-06-05 13:17:41

标签: java image model-view-controller javafx

我正在尝试创建一个允许用户打开图像文件并在窗格中显示它的应用程序。我已经选择了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类来更新我的视图中的pane,该视图在.fxml文件中定义如下:

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

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

1 个答案:

答案 0 :(得分:2)

您需要将FXML文件中的元素注入控制器,以便您可以在那里访问它。请参阅tutorial(“向表中添加行”,清单3-14和3-16部分)或documentation

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

<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中,您可以通过选择fx:id设置Pane,然后在“代码”部分下输入其值,该部分是右侧窗格的底部:

enter image description here