[英]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.