[英]JavaFX Setting an Image to ImageView after selecting it
我想借助JFileChooser在HDD上選擇一張圖片,並將其顯示在GUI中。
問題是我無法將所選圖像設置為ImageView。 我想我做的是完全錯誤的事情,但是我也嘗試了其他各種方式來顯示它,例如使用BufferedImage,但是對我來說沒有任何用。
我沒有落后,請幫助我。
控制器:
package application; import java.io.File; import java.net.MalformedURLException; import javax.swing.JFileChooser; import javax.swing.filechooser.FileSystemView; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.image.ImageView; public class WindowController { @FXML private Button btn_load; @FXML private TextField text_path; @FXML private ImageView img_frame; public Main main; public void setMain(Main main) { this.main = main; } @FXML public void handle_load() throws MalformedURLException{ JFileChooser chooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); int returnValue = chooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { text_path.setText(chooser.getSelectedFile().getAbsolutePath()); File file = new File(chooser.getSelectedFile().getAbsolutePath()); String localURL = file.toURI().toURL().toString(); img_frame.setImage(localURL); } } }
和fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="700.0" prefWidth="900.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.WindowController">
<children>
<ImageView fx:id="img_frame" fitHeight="516.0" fitWidth="627.0" layoutX="142.0" layoutY="114.0" pickOnBounds="true" preserveRatio="true" AnchorPane.bottomAnchor="97.0" AnchorPane.leftAnchor="142.0" AnchorPane.rightAnchor="142.0" AnchorPane.topAnchor="114.0" />
<HBox layoutX="14.0" layoutY="14.0" prefHeight="25.0" prefWidth="885.0" AnchorPane.leftAnchor="14.0" AnchorPane.rightAnchor="12.0">
<children>
<Button fx:id="btn_load" mnemonicParsing="false" onAction="#handle_load" text="Load Image" HBox.hgrow="NEVER" />
<TextField fx:id="text_path" prefHeight="25.0" prefWidth="0.0" HBox.hgrow="SOMETIMES" />
</children>
</HBox>
</children>
</AnchorPane>
而不是將其添加到網址中,只需添加
img_view.setImage(new Image(url));
它將解決您的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.