JavaFX ImageView neues Bild zuweisen

balkongenie

Mitglied
Hallo zusammen,

ich möchte einem schon bestehenden ImageView ein anderes Bild zuweisen, welches sich hinter dem Pfad "C:/Fotobox/20160125_05.JPG" befindet. Der ImageView wurde mit dem SceneBuilder erstellt und enthält bereits ein Bild aus diesem Ordner. Leider bekomme ich immer eine InvocationTargetException caused by NullPointerException in der Zeile, in der ich per setImage das neue Bild zuweisen möchte. Hier mein (inzwischen aufs Wesentliche abgespeckter) Code:

Java:
package application;

import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;

public class FensterController implements Initializable{
   @FXML private AnchorPane fenster_view;
   @FXML private Button btn_home_aufnahme;
   @FXML private Pane viewport;
   @FXML private ImageView img_view_film01;
   @FXML private ImageView img_view_film02;
   @FXML private ImageView img_view_film03;
   @FXML private ImageView img_view_film04;
   @FXML private ImageView img_view_film05;
  
   @Override
   public void initialize(URL arg0, ResourceBundle arg1) {
   }  
   
   @FXML
   public void btnAufnahmeClicked(Event e){    
     fotosLaden(); //Aktualisiere ImageViews
   }
   
   public void fotosLaden(){  
     img_view_film01.setImage(
       new Image(
         new File("file:C:/Fotobox/20160125_05.JPG").toURI().toString()
       )
     );
   }
}

Erkennt ihr den Fehler? Das Bild soll später automatisch per File abgerufen werden, der Einfachheithalber habe ich nun ersteinmal den Absoluten Pfad hineinkopiert

Beste Grüße,
Stefan
 
wieso verkettest Du alles in einer Zeile beim lesen des Bildes ohne auf null zu prüfen?

Du willst die Datei per URI angeben? Dann solltest Du einmal schauen, die das richtig geht:

https://en.m.wikipedia.org/wiki/File_URI_scheme

Und dann schau den Aufruf an! Du erstellst eine File Instanz, auf der Du toUri und dann toString aufrufst?

So wie du das angegeben hast wird er keine Datei laden. Ich hätte da nur den pfad der datei erwartet und gewissen Krimskrams halt eher weggelassen.
 
Ehrlich gesagt weiß ich immer noch nicht, wie ich das Ganze nun anlege. Ich stehe noch unglaublich auf dem Schlauch...
Java:
        Image img = new Image("file:C:/Fotobox/20160125_05.JPG");
        System.out.println("Image img: "+img.toString());   
        img_view_film01.setImage( img ); // in dieser Zeile wird die NullPointerException geworfen

Ergibt als Ausgabe:

Aufnahme geklickt
Image img: javafx.scene.image.Image@2b90eb44
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(Unknown Source)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1500(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
... 49 more
Caused by: java.lang.NullPointerException
at application.FensterController.fotosLaden(FensterController.java:90)
at application.FensterController.btnAufnahmeClicked(FensterController.java:63)
... 58 more

Hiiiilfe 😉
 
Noch einmal:
https://en.wikipedia.org/wiki/File_URI_scheme
Was lesen wir da?
Format
A file URI takes the form of


where host is the fully qualified domain name of the system on which the path is accessible, and path is a hierarchical directory path of the form directory/directory/.../name. If host is omitted, it is taken to be "localhost", the machine from which the URL is being interpreted. Note that when omitting host, the slash is not omitted (while "file:///foo.txt" is valid, "file://foo.txt" is not, although some interpreters manage to handle the latter).

[RFC 3986] includes additional information about the treatment of ".." and "." segments in URIs.
 
also weder
Java:
Image img = new Image("file://localhost/C:/Fotobox/20160125_05.JPG");
img_view_film01.setImage( img ); // in dieser Zeile wird die NullPointerException geworfen
noch
Java:
Image img = new Image("file:///C:/Fotobox/20160125_05.JPG");
img_view_film01.setImage( img ); // in dieser Zeile wird die NullPointerException geworfen
funktionieren bei mir. Ist ja nett, dass du mich an der Hand nimmst und Stück für Stück zur Lösung führst, aber ich bräuchte da doch noch einen Hinweis...
 
Also das Erste ist definitiv falsch, du hast keinen Netzwerkpfad, also brauchst du auch kein localhost.
Beim Zweiten: Es sieht richtig aus, aber da ich nicht verifizieren kann, dass das File existiert und ich nicht auf Windows arbeite...

Schau mal hier:
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/image/Image.html

Der Konstruktor nimmt auch InputStreams, also versuche dich mal an einem FileInputStream:
Java:
Image img = new Image(new FileInputStream(new File("C:\Fotobox\20160125_05.JPG")));
Wenn das nicht geht: Wir bräuchten dann mal den StackTrace und dann wird es Remote schwer. Versuch dich mal.

Ganz oben seh ich gerade, das du eine NullPointer hattest - ist das immer noch so?
 
Vielleicht nähern wir uns dem Ziel 😉 Danke für eure Unterstützung! Leider funktioniert es immer noch nicht....
Der letzte Vorschlag würde die Sache theoretisch sogar vereinfachen, da ich die Bilder zuerst auslese und in einem Files[] Array speichere. Im Ordner befinden sich 6 Bilder, von denen die ersten 5 in ImageViews angezeigt werden sollen. Diese sind JPG-Dateien werden vor dem Anzeigen so sortiert, dass das neueste Bild am Anfang steht. Die Ausgabe der for-Schleife zeigt, dass die Dateien tatsächlich vorhanden sind.

Java:
    public void fotosLaden() throws FileNotFoundException{
        //Lege Array mit allen Dateien im Ordner Fotobox an
        File file = new File("C:/Fotobox/");
        File[] files = file.listFiles();
        //Sortieren: Neuere Datei oben
        Arrays.sort(files, new Comparator<Object>() {
            public int compare(Object o1, Object o2) {
                File f0 = (File) o1, f1 = (File) o2;
                long last0 = f0.lastModified(), last1 = f1.lastModified();
                if (last0 > last1)
                    { return -1; }
                else if (last0 < last1)
                    { return 1; }
                else
                    { return 0; }
            }
        });
      
        //Gebe die Dateinamen wie oben sortiert aus
        for (int i = 0; i < files.length; i++)
            { System.out.println(files[i]); }
       
        Image img = new Image(new FileInputStream(files[0]));
        img_view_film01.setImage( img ); // in dieser Zeile wird die NullPointerException geworfen
    }

Die Ausgabe sieht folgendermaßen aus:
Aufnahme geklickt
C:\Fotobox\20160219_210842.jpg
C:\Fotobox\20160217_175938.jpg
C:\Fotobox\20160217_121207.jpg
C:\Fotobox\20160125_06.JPG
C:\Fotobox\20160125_05.JPG
C:\Fotobox\20160125_02.JPG
mit dem Error
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(Unknown Source)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1500(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
... 49 more
Caused by: java.lang.NullPointerException
at application.FensterController.fotosLaden(FensterController.java:94)
at application.FensterController.btnAufnahmeClicked(FensterController.java:67)
... 58 more
 
@Blender3D das nehme ich gerne in den Code auf🙂, löst aber immer noch nicht mein Problem...😵
Es kann doch nicht eine so große Kunst zu sein, ein File in einen ImageView zu stecken... 🙁
Hier die aktuelle Funktion:

Java:
public void fotosLaden() throws FileNotFoundException{
        //Lege Array mit allen Dateien im Ordner Fotobox an
        File file = new File("C:/Fotobox/");
        File[] files = file.listFiles();
        //Sortieren: Neuere Datei oben
        Arrays.sort(files, new Comparator<Object>() {
            public int compare(Object o1, Object o2) {
                File f0 = (File) o1, f1 = (File) o2;
                long last0 = f0.lastModified(), last1 = f1.lastModified();
                return (int)(last1-last0);
            }
        });
      
        //Gebe die Dateinamen wie oben sortiert aus
        for (int i = 0; i < files.length; i++)
            { System.out.println(files[i]); }
        
        //Sortiere erstes Foto in den TextView ein
        Image img = new Image(new FileInputStream(files[0]));
        img_view_film01.setImage( img ); // in dieser Zeile wird die NullPointerException geworfen
    }
 
Im Kopf der Klasse wird sie deklariert
Java:
public class FensterController implements Initializable{
    @FXML private AnchorPane fenster_view;
    @FXML private Button btn_home_aufnahme;
    @FXML private Pane viewport;
   
    @FXML private ImageView img_view_film01;
    @FXML private ImageView img_view_film02;
    @FXML private ImageView img_view_film03;
    @FXML private ImageView img_view_film04;
    @FXML private ImageView img_view_film05;

(...)

und da sie auch im FXML Dokument
HTML:
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.net.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.*?>

<AnchorPane fx:id="fenster_view" layoutX="0.0" layoutY="0.0" maxHeight="1024.0" maxWidth="768.0" minHeight="1024.0" minWidth="768.0" prefHeight="1024.0" prefWidth="768.0" styleClass="root" translateX="0.0" translateY="0.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="application.FensterController">
  <children>
    <Button id="btn_home_test" layoutX="67.0" layoutY="605.0" mnemonicParsing="false" opacity="0.3" prefHeight="110.0" prefWidth="332.0" text="Tester">
      <font>
        <Font size="40.0" fx:id="x1" />
      </font>
    </Button>
    <Button fx:id="btn_home_aufnahme" font="$x1" layoutX="67.0" layoutY="356.0" mnemonicParsing="false" onAction="#btnAufnahmeClicked" opacity="0.81" prefHeight="227.0" prefWidth="332.0" text="Aufnahme" />
    <ImageView id="img_view_film01" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="26.0" pickOnBounds="true" preserveRatio="true">
      <image>
        <Image url="@../../../../../../../Fotobox/20160125_02.JPG" />
      </image>
    </ImageView>
    <ImageView id="img_view_film02" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="213.0" pickOnBounds="true" preserveRatio="true" />
    <ImageView id="img_view_film03" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="401.0" pickOnBounds="true" preserveRatio="true" />
    <ImageView id="img_view_film04" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="571.0" pickOnBounds="true" preserveRatio="true" />
    <ImageView id="img_view_film05" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="741.0" pickOnBounds="true" preserveRatio="true" />
  </children>
  <stylesheets>
    <URL value="@Fenster.css" />
  </stylesheets>
</AnchorPane>
enthalten ist, sollte sie auch initialisiert sein - oder habe ich da was falsch verstanden? (ich bin neu in FXML...). Dem ersten ImageView habe ich über den SceneBuilder mal schon ein Foto hinzugefügt, das hat funktioniert (siehe FXML-Code)
 
Also ich verwende JavaFX nicht. Ich halte nicht sehr viel von dem Ganzen OVerhead. Ich habe einen ImageView test aus dem Netz probiert. Und hatte gleich denselben fehler wie Du.
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
Ursache war hier eine nicht güliger Filename für Image.
Es wurden unzälige Fehler ausgegeben ( wahrscheinlich Overhead von FX ). Aber ich konnte das Problem beheben und dann lief das Ding. Ich poste Dir mal den Code. Ob es Dir hilft musst Du selbst feststellen.
Code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class HelloMenu extends Application {

    @Override public void start(Stage stage) {
        // load the image
         File file = new File("/home/budy/execute/Images/donald.png");
        Image image = null;;
        try {
            image = new Image(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.exit(1);
        }

        // simple displays ImageView the image as is
        ImageView iv1 = new ImageView();
        iv1.setImage(image);

        // resizes the image to have width of 100 while preserving the ratio and using
        // higher quality filtering method; this ImageView is also cached to
        // improve performance
        ImageView iv2 = new ImageView();
        iv2.setImage(image);
        iv2.setFitWidth(100);
        iv2.setPreserveRatio(true);
        iv2.setSmooth(true);
        iv2.setCache(true);

        // defines a viewport into the source image (achieving a "zoom" effect) and
        // displays it rotated
        ImageView iv3 = new ImageView();
        iv3.setImage(image);
        Rectangle2D viewportRect = new Rectangle2D(40, 35, 110, 110);
        iv3.setViewport(viewportRect);
        iv3.setRotate(90);

        Group root = new Group();
        Scene scene = new Scene(root);
        scene.setFill(Color.BLACK);
        HBox box = new HBox();
        box.getChildren().add(iv1);
        box.getChildren().add(iv2);
        box.getChildren().add(iv3);
        root.getChildren().add(box);

        stage.setTitle("ImageView");
        stage.setWidth(415);
        stage.setHeight(200);
        stage.setScene(scene);
        stage.sizeToScene();
        stage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}
 
das obige Problem war dumm, ich hatte aus versehen den Ordner statt der Datei übergeben. Nachdem ich das wieder geändert hatte, werden mir nun zwar keine Fehler mehr geschmissen, allerdings tut sich in der GUI immer noch nichts -.- das ist doch zum Verzweifeln! Hier der aktuelle Code:

Controller-Klasse:
Java:
package application;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Comparator;
import java.util.ResourceBundle;

import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;

public class FensterController implements Initializable{
    @FXML private AnchorPane fenster_view;
    @FXML private Button btn_home_aufnahme;
    @FXML private Pane viewport;
 
    @FXML private ImageView img_view_film00;
    @FXML private ImageView img_view_film01;
    @FXML private ImageView img_view_film02;
    @FXML private ImageView img_view_film03;
    @FXML private ImageView img_view_film04;

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
    }
 
    @FXML
    public void btnAufnahmeClicked(Event e) throws FileNotFoundException, MalformedURLException{
        System.out.println("Aufnahme geklickt");     
        fotosLaden(); //Aktualisiere ImageViews
    }
 
    public void fotosLaden() throws FileNotFoundException, MalformedURLException{
        //Lege Array mit allen Dateien im Ordner Fotobox an
        File file = new File("D:/Fotobox/");
        File[] files = file.listFiles();
        //Sortieren: Neuere Datei oben
        Arrays.sort(files, new Comparator<Object>() {
            public int compare(Object o1, Object o2) {
                File f0 = (File) o1, f1 = (File) o2;
                long last0 = f0.lastModified(), last1 = f1.lastModified();
                return (int)(last1-last0);
            }
        });
    
        //Gebe die Dateinamen wie oben sortiert aus
        for (int i = 0; i < files.length; i++)
            { System.out.println(files[i]); }
     
        //Sortiere die Fotos in den ImageView ein
        Image img_film00 = null;
        Image img_film01 = null;
        Image img_film02 = null;
        Image img_film03 = null;
        Image img_film04 = null;

        try {
            img_film00 = new Image(new FileInputStream(files[0]));
            img_film01 = new Image(new FileInputStream(files[1]));
            img_film02 = new Image(new FileInputStream(files[2]));
            img_film03 = new Image(new FileInputStream(files[3]));
            img_film04 = new Image(new FileInputStream(files[4]));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.exit(1);
        }
     
        img_view_film00 = new ImageView(img_film00);
        img_view_film01 = new ImageView(img_film01);
        img_view_film02 = new ImageView(img_film02);
        img_view_film03 = new ImageView(img_film03);
        img_view_film04 = new ImageView(img_film04);
    }
}

FXML-Dokument:
HTML:
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.net.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.*?>

<AnchorPane fx:id="fenster_view" layoutX="0.0" layoutY="0.0" maxHeight="1024.0" maxWidth="768.0" minHeight="1024.0" minWidth="768.0" prefHeight="1024.0" prefWidth="768.0" styleClass="root" translateX="0.0" translateY="0.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="application.FensterController">
  <children>
    <Button id="btn_home_test" layoutX="67.0" layoutY="605.0" mnemonicParsing="false" opacity="0.3" prefHeight="110.0" prefWidth="332.0" text="Tester">
      <font>
        <Font size="40.0" fx:id="x1" />
      </font>
    </Button>
    <Button fx:id="btn_home_aufnahme" font="$x1" layoutX="67.0" layoutY="356.0" mnemonicParsing="false" onAction="#btnAufnahmeClicked" opacity="0.81" prefHeight="227.0" prefWidth="332.0" text="Aufnahme" />
    <ImageView id="img_view_film00" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="26.0" pickOnBounds="true" preserveRatio="true">
      <image>
        <Image url="@../../../../../../../Fotobox/20160125_02.JPG" />
      </image>
    </ImageView>
    <ImageView id="img_view_film01" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="213.0" pickOnBounds="true" preserveRatio="true" />
    <ImageView id="img_view_film02" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="401.0" pickOnBounds="true" preserveRatio="true" />
    <ImageView id="img_view_film03" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="571.0" pickOnBounds="true" preserveRatio="true" />
    <ImageView id="img_view_film04" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="741.0" pickOnBounds="true" preserveRatio="true" />
  </children>
  <stylesheets>
    <URL value="@Fenster.css" />
  </stylesheets>
</AnchorPane>

Mit der Consolen-Ausgabe:
Aufnahme geklickt
D:\Fotobox\20160219_210842.jpg
D:\Fotobox\20160217_175938.jpg
D:\Fotobox\20160217_121207.jpg
D:\Fotobox\20160125_06.JPG
D:\Fotobox\20160125_05.JPG
D:\Fotobox\20160125_02.JPG

Muss ich noch irgendwo einen Befehl zum erneuern/neuen Anzeigen der GUI geben?

EDIT: Ein Blick in den Debugger hat ergeben, dass die ganzen Objekte zwar initialisiert werden, das Attribut ImageURL jedoch weiterhin auf null steht.. ?!..
 
Zuletzt bearbeitet:
Du erzeugst neue ImageView Instanzen anstatt die Bilder in den vorhandenen ImageView Objekten zu setzen.

Der fxml Loader erzeugt ja alle Objekte für Dich incl. der ImageView Instanzen, die dann angezeigt werden und Referenzen werden im Controler hinterlegt.

Nun überschreibst Du die Referenzen, was auf die Anzeige keinen Einfluss hat.

Also statt
img_view_film00 =new ImageView(img_film00);
ein
img_view_film00.setImage(img_film00);
 
Verstehe voll was du meinst - leider bekomme ich dann wieder die Fehlermeldung vom Beginn:
Aufnahme geklickt
D:\Fotobox\20160219_210842.jpg
D:\Fotobox\20160217_175938.jpg
D:\Fotobox\20160217_121207.jpg
D:\Fotobox\20160125_06.JPG
D:\Fotobox\20160125_05.JPG
D:\Fotobox\20160125_02.JPG
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(Unknown Source)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1500(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
... 49 more
Caused by: java.lang.NullPointerException
at application.FensterController.fotosLaden(FensterController.java:100)
at application.FensterController.btnAufnahmeClicked(FensterController.java:67)
... 58 more

mit Zeile 100:
Java:
img_view_film00.setImage(img_film00);
 
Schau doch mal im Debugger, ob die Variablen überhaupt gesetzt sind. Ich habe jetzt einmal selbst getestet und das Problem bei Dir könnte sein, dass Du in dem fxml nur id= statt fx:id= hast. Also bleiben Deine Variablen alle null und werden nicht zugewiesen.

Also statt
Code:
   <ImageView id="img_view_film01" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="213.0" pickOnBounds="true" preserveRatio="true" />
   <ImageView id="img_view_film02" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="401.0" pickOnBounds="true" preserveRatio="true" />
   <ImageView id="img_view_film03" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="571.0" pickOnBounds="true" preserveRatio="true" />
   <ImageView id="img_view_film04" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="741.0" pickOnBounds="true" preserveRatio="true" />

Code:
   <ImageView fx:id="img_view_film01" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="213.0" pickOnBounds="true" preserveRatio="true" />
   <ImageView fx:id="img_view_film02" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="401.0" pickOnBounds="true" preserveRatio="true" />
   <ImageView fx:id="img_view_film03" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="571.0" pickOnBounds="true" preserveRatio="true" />
   <ImageView fx:id="img_view_film04" fitHeight="159.0" fitWidth="212.0" layoutX="511.0" layoutY="741.0" pickOnBounds="true" preserveRatio="true" />
 
Der Vollständigkeit-Halber noch das kleine Test-Programm, welches das Setzen eines Bildes einmal zeigt:

sample.Main:
Java:
package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

sample.Controller:
Java:
package sample;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

import java.io.FileInputStream;

public class Controller {
    @FXML private Button testButton;
    @FXML private ImageView testImageView;

    @FXML public void testClicked(ActionEvent event) {
        try {
            try (FileInputStream stream = new FileInputStream("c:\\temp\\konrad.jpg")) {
                Image image = new Image(stream);
                testImageView.setImage(image);
            }
        } catch (Exception exception) {
            System.out.println(exception.getMessage());
            exception.printStackTrace();
        }
    }
}

sample.fxml:
Code:
<?importjavafx.scene.control.Button?>
<?importjavafx.scene.image.ImageView?>
<?importjavafx.scene.layout.GridPane?>
<GridPane fx:controller="sample.Controller"
          xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
    <Button GridPane.columnIndex="0" fx:id="testButton" text="Test" onAction="#testClicked" />
    <ImageView GridPane.columnIndex="1" fx:id="testImageView"  />

</GridPane>
 
Ahhhhhh made my day!! 🙂 es war tatsächlich das fx: was ich dort einfach vergessen hatte!!! 🙂 Danke für eure Geduld und Mühen! 🙂 Jippey, weiter gehts 😉
 
Arrays.sort(files, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
File f0 = (File) o1, f1 = (File) o2;
long last0 = f0.lastModified(), last1 = f1.lastModified();
return (int)(last1-last0);
}
});
Das wäre schöner so.
Code:
        Arrays.sort(files, new Comparator<File>() {
            public int compare(File f1, File f2) {
                return (int) (f2.lastModified() - f1.lastModified());
            }
        });
😉
 

Neue Themen


Zurück
Oben