JavaFX选择后将图像设置为ImageView
问题描述:
我想借助JFileChooser选择硬盘上的图片并将其显示在GUI中。
问题是我无法将所选图像设置为ImageView。我想我正在做一些完全错误的事情,但我也尝试过其他各种方式来显示它,例如使用BufferedImage,但没有为我工作。
我不明白这一点,请帮助我。JavaFX选择后将图像设置为ImageView
控制器:
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 {
\t
\t @FXML private Button btn_load;
\t @FXML private TextField text_path;
\t @FXML private ImageView img_frame;
\t
\t public Main main;
\t
\t public void setMain(Main main) {
\t \t this.main = main;
\t }
\t
\t @FXML
\t public void handle_load() throws MalformedURLException{
\t \t JFileChooser chooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
\t \t int returnValue = chooser.showOpenDialog(null);
\t \t
\t \t if (returnValue == JFileChooser.APPROVE_OPTION) {
\t \t \t text_path.setText(chooser.getSelectedFile().getAbsolutePath());
\t \t \t File file = new File(chooser.getSelectedFile().getAbsolutePath());
\t \t \t String localURL = file.toURI().toURL().toString();
\t \t \t img_frame.setImage(localURL);
\t \t }
\t }
}
而且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>
答
它添加到URL,而不是,只是添加
img_view.setImage(new Image(url));
它会解决您的问题
您需要将图像放入图像视图不是URL - img_frame.setImage(new Image(localURL)); –