[英]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
類來更新在.fxml文件中定義的視圖中的pane
,如下所示:
<Pane maxHeight="1.8" style="-fx-border-color: #000000;" GridPane.rowIndex="1"/>
因為它是我無法找到一種方法,因為我無法引用該pane
。
您需要將FXML文件中的元素注入到控制器中,以便可以在其中訪問它。 請參閱教程 (“向表添加行”一節,清單3-14和3-16)或文檔 。
基本上,您需要在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中,可以通過選擇Pane
,然后在“代碼”部分(即右窗格的底部)中輸入其值來設置fx:id
:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.