Java FXML:为什么我的 imageView 不显示,如何从我的计算机上传图像?

Java FXML: Why is my imageView not Showing, and how can I upload an image from my computer?

我正在做一个项目,我需要上传一张图片并对其应用一些过滤器。为此,我正在使用 javaFx FXML。这是我第一次使用这个工具,所以我有点迷茫。我使用 fxml 控制器创建了一个简单的界面,并添加了一些按钮和一个 imageView 字段。在图像视图字段中,我还添加了一个默认图像,在我应用它时它会正常显示,但当我实际 运行 项目时它不会显示图像,我看到的只是一个空白 space 其中图片应该是。有人知道为什么会这样吗? 另外,正如你们将在代码中看到的那样,我想知道如何访问 imageView src,以便我可以上传图像并使用 JFileChooser 随时更改它。非常感谢。

Controler

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fotofinish;

import java.awt.BorderLayout;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author user
 */
public class FXMLDocumentController implements Initializable {
    private JPanel      jpanel, jpanelbar;
     JLabel              image;
    private Label label;
    @FXML
    private Button filterGrayscaleButton;
    @FXML
    private Button filterSepiaButton;
    @FXML
    private Button filterInstantButton;
    @FXML
    private Button filterCustomButton;
    @FXML
    private Button filterNoneButton;
    @FXML
    private Slider brightnessSlider;
    @FXML
    private Slider contrastSlider;
    @FXML
    private ToggleGroup brushTypeRadioGroup;
    @FXML
    private RadioButton brushTypeCircleRadioButton;
    @FXML
    private RadioButton brushTypeSpraypaintRadioButton;
    @FXML
    private RadioButton brushTypeSquareRadioButton;
    @FXML
    private MenuItem menubarHelpFotoFinishHelpMenuItem;
    @FXML
    private MenuItem menubarHelpAboutMenuItem;
    @FXML
    private Label filtersLabel;
    @FXML
    private Label sliderLabel;
    @FXML
    private Label brightnessLabel;
    @FXML
    private Label contrastLabel;
    @FXML
    private Label drawingLabel;
    @FXML
    private ColorPicker brushColorPicker;
    @FXML
    private Label brushTypeLabel;
    @FXML
    private Label brushSizeLabel;
    @FXML
    private TextField brushSizeTextField;
    @FXML
    private MenuItem menubarFileNew;
    @FXML
    private MenuItem menubarFileOpen;
    @FXML
    private MenuItem menubarFileGalleryButterfly;
    @FXML
    private MenuItem menubarFileGalleryTeddyBear;
    @FXML
    private MenuItem menubarFileGalleryPrincess;
    @FXML
    private MenuItem menubarFileGalleryFirefighter;
    @FXML
    private MenuItem menubarFileSave;
    @FXML
    private MenuItem menubarFileSaveAs;
    @FXML
    private MenuItem menubarFileQuit;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        //TODO: make call function only when value changes by certain threshold
        brightnessSlider.valueProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                System.out.println("TODO: brightness changed to " + newValue);
            }
        });

        contrastSlider.valueProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                System.out.println("TODO: contrast changed to " + newValue);
            }
        });
    }

    @FXML
    private void applyFilterGrayscale(ActionEvent event) {
        System.out.println("TODO: grayscale filter applied");
    }

    @FXML
    private void applyFilterSepia(ActionEvent event) {
        System.out.println("TODO: sepia filter applied");
    }

    @FXML
    private void applyFilterInstant(ActionEvent event) {
        System.out.println("TODO: instant filter applied");
    }

    @FXML
    private void createFilterCustomPopup(ActionEvent event) {
        System.out.println("TODO: launched custom filter popup");
    }

    @FXML
    private void applyFilterNone(ActionEvent event) {
        System.out.println("TODO: none filter applied");
    }

    @FXML
    private void changeBrushTypeCircle(ActionEvent event) {
        System.out.println("TODO: brush type changed to circle");
    }

    @FXML
    private void changeBrushTypeSquare(ActionEvent event) {
        System.out.println("TODO: brush type changed to square");
    }

    @FXML
    private void changeBrushTypeSpraypaint(ActionEvent event) {
        System.out.println("TODO: brush type changed to spraypaint");
    }

    @FXML
    private void displayHelpDoc(ActionEvent event) {
        System.out.println("TODO: launched help document");
    }

    @FXML
    private void displayAboutDialog(ActionEvent event) {
        System.out.println("TODO: created about dialog");
    }

    @FXML
    private void changeBrushColor(ActionEvent event) {
        System.out.println("TODO: brush color changed to <BRUSH COLOR>");
    }

    @FXML
    private void adjustBrushSize(ActionEvent event) {
        System.out.println("TODO: brush size changed to <BRUSH SIZE>");
    }

    @FXML
    private void openFile(ActionEvent event) {
        System.out.println("TODO: launched file picker");
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.showOpenDialog(null);
        File f = fileChooser.getSelectedFile();
        System.out.print(f.getAbsolutePath());
        //image = new JLabel("", new ImageIcon(f.getAbsolutePath()), JLabel.CENTER);
        //jpanel.add(image, BorderLayout.CENTER);
        //jpanel.revalidate(); //ADD THIS AS WELL
        //jpanel.repaint();
    }

    @FXML
    private void openFileGalleryButterfly(ActionEvent event) {
        System.out.println("TODO: opened butterfly file from gallery");
    }

    @FXML
    private void openFileGalleryTeddyBear(ActionEvent event) {
        System.out.println("TODO: opened teddy bear file from gallery");
    }

    @FXML
    private void openFileGalleryPrincess(ActionEvent event) {
        System.out.println("TODO: opened princess file from gallery");
    }

    @FXML
    private void openFileGalleryFirefighter(ActionEvent event) {
        System.out.println("TODO: opened firefighter file from gallery");
    }

    @FXML
    private void saveFile(ActionEvent event) {
        System.out.println("TODO: saved file");
    }


    @FXML
    private void saveFileAs(ActionEvent event) {
        System.out.println("TODO: launched file save as dialog");
    }


    @FXML
    private void quit(ActionEvent event) {
        System.exit(1);
        System.out.println("TODO: quit program");
    }

    @FXML
    private void createNewFile(ActionEvent event) {
        System.out.println("TODO: created new file");
    }
}

FXML`

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.input.*?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="700.0" prefWidth="1200.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="fotofinish.FXMLDocumentController">
   <top>
      <MenuBar BorderPane.alignment="CENTER">
        <menus>
          <Menu mnemonicParsing="false" text="File">
            <items>
                  <MenuItem fx:id="menubarFileNew" mnemonicParsing="false" onAction="#createNewFile" text="New">
                     <accelerator>
                        <KeyCodeCombination alt="UP" code="N" control="DOWN" meta="UP" shift="UP" shortcut="UP" />
                     </accelerator>
                  </MenuItem>
                  <SeparatorMenuItem mnemonicParsing="false" />
                  <MenuItem fx:id="menubarFileOpen" mnemonicParsing="false" onAction="#openFile" text="Open">
                     <accelerator>
                        <KeyCodeCombination alt="UP" code="O" control="DOWN" meta="UP" shift="UP" shortcut="UP" />
                     </accelerator>
                  </MenuItem>
                  <Menu mnemonicParsing="false" text="Open from Gallery">
                    <items>
                      <MenuItem fx:id="menubarFileGalleryButterfly" mnemonicParsing="false" onAction="#openFileGalleryButterfly" text="Butterfly" />
                        <MenuItem fx:id="menubarFileGalleryTeddyBear" mnemonicParsing="false" onAction="#openFileGalleryTeddyBear" text="Teddy Bear" />
                        <MenuItem fx:id="menubarFileGalleryPrincess" mnemonicParsing="false" onAction="#openFileGalleryPrincess" text="Princess" />
                        <MenuItem fx:id="menubarFileGalleryFirefighter" mnemonicParsing="false" onAction="#openFileGalleryFirefighter" text="Firefighter" />
                    </items>
                  </Menu>
                  <SeparatorMenuItem mnemonicParsing="false" />
                  <MenuItem fx:id="menubarFileSave" mnemonicParsing="false" onAction="#saveFile" text="Save">
                     <accelerator>
                        <KeyCodeCombination alt="UP" code="S" control="DOWN" meta="UP" shift="UP" shortcut="UP" />
                     </accelerator>
                  </MenuItem>
                  <MenuItem fx:id="menubarFileSaveAs" mnemonicParsing="false" onAction="#saveFileAs" text="Save As">
                     <accelerator>
                        <KeyCodeCombination alt="UP" code="S" control="DOWN" meta="UP" shift="DOWN" shortcut="UP" />
                     </accelerator>
                  </MenuItem>
                  <SeparatorMenuItem mnemonicParsing="false" />
              <MenuItem fx:id="menubarFileQuit" mnemonicParsing="false" onAction="#quit" text="Quit">
                     <accelerator>
                        <KeyCodeCombination alt="UP" code="C" control="DOWN" meta="UP" shift="UP" shortcut="UP" />
                     </accelerator></MenuItem>
            </items>
          </Menu>
          <Menu mnemonicParsing="false" text="Help">
            <items>
              <MenuItem fx:id="menubarHelpFotoFinishHelpMenuItem" mnemonicParsing="false" onAction="#displayHelpDoc" text="Foto Finish Help">
                     <accelerator>
                        <KeyCodeCombination alt="UP" code="F1" control="UP" meta="UP" shift="UP" shortcut="UP" />
                     </accelerator></MenuItem>
                  <MenuItem fx:id="menubarHelpAboutMenuItem" mnemonicParsing="false" onAction="#displayAboutDialog" text="About" />
            </items>
          </Menu>
        </menus>
      </MenuBar>
   </top>
   <center>
      <SplitPane dividerPositions="0.14941569282136896" prefHeight="160.0" prefWidth="200.0" BorderPane.alignment="CENTER">
        <items>
          <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
               <children>
                  <VBox layoutX="-11.0" layoutY="25.0" prefHeight="200.0" prefWidth="100.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                     <children>
                        <Label fx:id="filtersLabel" text="Filters" />
                        <Button fx:id="filterGrayscaleButton" mnemonicParsing="false" onAction="#applyFilterGrayscale" text="Grayscale" />
                        <Button fx:id="filterSepiaButton" mnemonicParsing="false" onAction="#applyFilterSepia" text="Sepia" />
                        <Button fx:id="filterInstantButton" mnemonicParsing="false" onAction="#applyFilterInstant" text="Instant" />
                        <Button fx:id="filterCustomButton" mnemonicParsing="false" onAction="#createFilterCustomPopup" text="Custom" />
                        <Button fx:id="filterNoneButton" mnemonicParsing="false" onAction="#applyFilterNone" text="None" />
                        <Label fx:id="sliderLabel" text="Sliders" />
                        <GridPane prefHeight="310.0" prefWidth="175.0">
                          <columnConstraints>
                            <ColumnConstraints halignment="CENTER" hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                            <ColumnConstraints halignment="CENTER" hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                          </columnConstraints>
                          <rowConstraints>
                            <RowConstraints maxHeight="88.0" minHeight="10.0" prefHeight="23.0" vgrow="SOMETIMES" />
                            <RowConstraints maxHeight="290.0" minHeight="50.0" prefHeight="287.0" vgrow="SOMETIMES" />
                          </rowConstraints>
                           <children>
                              <Label fx:id="brightnessLabel" text="Brightness" />
                              <Label fx:id="contrastLabel" text="Contrast" GridPane.columnIndex="1" />
                              <Slider fx:id="brightnessSlider" min="-100.0" minorTickCount="5" orientation="VERTICAL" showTickLabels="true" showTickMarks="true" snapToTicks="true" GridPane.rowIndex="1" />
                              <Slider fx:id="contrastSlider" min="-100.0" minorTickCount="5" orientation="VERTICAL" showTickLabels="true" showTickMarks="true" snapToTicks="true" GridPane.columnIndex="1" GridPane.rowIndex="1" />
                           </children>
                        </GridPane>
                        <Label fx:id="drawingLabel" text="Drawing" />
                        <ColorPicker fx:id="brushColorPicker" onAction="#changeBrushColor" />
                        <Label fx:id="brushTypeLabel" text="Brush Type" />
                        <RadioButton fx:id="brushTypeCircleRadioButton" mnemonicParsing="false" onAction="#changeBrushTypeCircle" selected="true" text="Circle">
                           <toggleGroup>
                              <ToggleGroup fx:id="brushTypeRadioGroup" />
                           </toggleGroup>
                        </RadioButton>
                        <RadioButton fx:id="brushTypeSquareRadioButton" mnemonicParsing="false" onAction="#changeBrushTypeSquare" text="Square" toggleGroup="$brushTypeRadioGroup" />
                        <RadioButton fx:id="brushTypeSpraypaintRadioButton" mnemonicParsing="false" onAction="#changeBrushTypeSpraypaint" text="Spraypaint" toggleGroup="$brushTypeRadioGroup" />
                        <Label fx:id="brushSizeLabel" text="Brush Size" />
                        <TextField fx:id="brushSizeTextField" onAction="#adjustBrushSize" />
                     </children>
                  </VBox>
               </children>
            </AnchorPane>
          <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="369.0" prefWidth="465.0">
               <children>
                  <ImageView fx:id="AnchorPaneScrollPaneImageView" fitHeight="479.0" fitWidth="585.0" pickOnBounds="true" preserveRatio="true">
                     <image>
                        <Image url="@../../../../Pictures/images.png" />
                     </image>
                  </ImageView>
               </children>
            </AnchorPane>
        </items>
      </SplitPane>
   </center>
</BorderPane>
`

您需要在 Java 控制器中创建对 ImageView you defined in FXML. You do this using the @FXML annotation 的引用。

目前你有这个:

<ImageView fx:id="AnchorPaneScrollPaneImageView" ...

这行得通,但名称有点长,并且不遵循 Java/FXML 实例变量的起始 ID 小写的命名约定(这也是错误的,因为您没有 ScrollPane ), 所以只需将其更改为:

<ImageView fx:id="imageView" ...

然后在您的代码中插入对它的引用(就像您对所有其他 FXML 定义的元素所做的那样):

@FXML
private ImageView imageView;

要select一张图片你可以写:

FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Image File");
fileChooser.getExtensionFilters().addAll(
     new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
);
File selectedFile = fileChooser.showOpenDialog(mainStage);

当你想给它设置图片时,你可以这样做:

if (selectedFile != null) {
    imageView.setImage(selectedFile.toURI().toURL());
}

注意:我还没有测试上面的代码片段。

一边

混合使用 Swing 和 JavaFX 是不可取的,除非你真的需要它,如果你只是学习 FXML,根本不建议这样做。从您的代码中删除 java.awt 和 javax.swing 导入及其用法,并将功能替换为对应的 JavaFX。例如,JavaFX 包括 FileChooser, so you should use that rather than a JFileChooser.