我想在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>
答案 0 :(得分:1)
而不是将其添加到网址,只需添加
即可img_view.setImage(new Image(url));
它将解决您的问题