JavaFX getting path of image store in Imageview with the help of filechooser need help D:

5.3k views Asked by At

my question is that I need help with getting the path from a image within a imageview in fxml file as I need to store the path of the image in an object. I am using a filechooser to input image into the imageView. I am planning to store that path into a object and claim it out at a later time like a profile page would keep the profile picture. I know it is abit brief but I hope if you guys got any way of helping me out it will be appreciated.

So based on the comments I edited: My problem is I cannot claim the URL of the image path although i using a filechooser. I have actually remove out all the relevant parts regarding the claiming of URL that i made as i cannot claim it out.

    package orgRegistrationtest;

public class OrgRegistrationController {

@FXML
private JFXHamburger hamburger;

@FXML
private JFXTextField email;

@FXML
private JFXCheckBox health;

@FXML
private JFXCheckBox animal;

@FXML
private JFXCheckBox children;

@FXML
private JFXCheckBox elderly;

@FXML
private JFXCheckBox environment;

@FXML
private JFXCheckBox others;

@FXML
private JFXTextField name;

@FXML
private JFXTextField contact;

@FXML
private JFXTextField address;

@FXML
private JFXPasswordField password;

@FXML
private JFXPasswordField password2;

@FXML
private JFXTextArea desc;

//pic not added 

@FXML
private ImageView pic;

@FXML
private JFXButton upload;

@FXML
private JFXButton clear;

@FXML
private JFXButton confirm;

@FXML
private JFXDrawer drawer;

@FXML
void handleClear(ActionEvent event) {

}


private String type=null;



@FXML

     private void handleConfirmButtonAction(ActionEvent event) throws IOException {

        if(health.isSelected())
            type=health.getText();
        if(animal.isSelected()){
            type+=";"+animal.getText();
        }
        if(children.isSelected()){
            type+=";"+children.getText();
        }
        if(elderly.isSelected()){
            type+=";"+elderly.getText();
        }
        if(environment.isSelected()){
            type+=";"+environment.getText();
            }
        if(others.isSelected()){
            type+=";"+others.getText();
        }

        String Email=email.getText();
        String Password = password.getText();
        String Password2=password2.getText();
        String Name = name.getText();
        String Contact= contact.getText();
        String Address=address.getText();
        String Type = ""+type;
        String Desc = desc.getText();
        //String url = pic.getImage()._____
        //.getURL(); i know getURL is not inside same for getPath();
        // So how am i able to claim the Path of the Image and store it?


        OrgData table = new OrgData(Email,Password,Password2,Name, Contact,Address,Type,Desc,url);

        OrgDataDAO dao = new OrgDataDAO();
        dao.createFriend(table);




}




@FXML
public void handleUpload(ActionEvent t) {
    FileChooser fileChooser = new FileChooser();

    //Set extension filter


    //Show open file dialog
    File file = fileChooser.showOpenDialog(null);

    try {
        BufferedImage bufferedImage = ImageIO.read(file);
        Image image = SwingFXUtils.toFXImage(bufferedImage, null);
        pic.setImage(image);
    } catch (IOException ex) {
        System.out.println(ex);
    }
}


private Main Main;

public Main getMainApp() {
    return Main;
}

// setter for mainApp
public void setMainApp(Main testmainApp) {
    this.Main = testmainApp;
}

This is the model I have I never put in a String for the URL yet as i unable to sort of claim it out and there may be a better way to do instead of using the path although I did try out and it give me nothing.

  public class OrgData implements Serializable {
private String email, pw, pw2, name, contact, address, type, desc,url;

final static ObservableList<OrgData> data = FXCollections.observableArrayList();


public OrgData(String email, String pw, String pw2, String name, String contact, String address, String type,
        String desc,String url) {
    super();
    this.email = email;
    this.pw = pw;
    this.pw2 = pw2;
    this.name = name;
    this.contact = contact;
    this.address = address;
    this.type = type;
    this.desc = desc;
    //this.url = url;
}

//public String getUrl() {
//  return url;
//}

//public void setUrl(String url) {
//    this.url= url;
//}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPw() {
    return pw;
}

public void setPw(String pw) {
    this.pw = pw;
}

public String getPw2() {
    return pw2;
}

public void setPw2(String pw2) {
    this.pw2 = pw2;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getContact() {
    return contact;
}

public void setContact(String contact) {
    this.contact = contact;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getType() {
    return type;
}



public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}



public static ObservableList<OrgData> getData() {
    return data;
}

public String toString(){
    return "["+email+","+pw+","+name+","+contact+","+address+","+type+","+desc+","+url+"]";
}

So this is the DAO where I save the file details at the end after users has click on the registered button and stored in the OrgRegData.dat file. So like I said, My problem is that I am unable to take the path from the imageView image that i pick from the filechooser and stored it in to my model even as a String as there is no getPath() or getURL(); sort of method after clicking on the registered. I am not using a database or anything just using files and text files to store the data and reading the data from the files, so I hope is more clearer now with my problem

    public class OrgDataDAO {
private static final String Friend_File="OrgRegData.dat";
private File dataFile;


public OrgDataDAO() {
    Path dPath = FileSystems.getDefault().getPath("resources/data/",Friend_File);
    dataFile=new File(dPath.toString());     
}

public ObservableList<OrgData> getAllFriends() {
    Scanner in;
    String record=null;
    String[] fields;
    ImageView[] images;

    ObservableList<OrgData> friends=FXCollections.observableArrayList();;
    try {
        in=new Scanner(dataFile);
        while (in.hasNextLine()) {
            record=in.nextLine();
            fields=record.split(",");
            String email=fields[0];
            String password=fields[1];
            String password2=fields[2];
            String name=fields[3];
            String contact = fields[4];
            String address=fields[5];
            String type=fields[6];
            String desc=fields[7];
            //String url = fields[8];

            OrgData f=new OrgData(email,password,password2,name,contact,address,type,desc,url);
            friends.add(f);
        }
        in.close();
    } catch (FileNotFoundException e) { 
        System.out.println("No record found!");
        //e.printStackTrace();
    }
    return friends;
}

/* assuming friend has a unique name, otherwise may return a list */
public OrgData getEvent(String email) {
    // TODO Auto-generated method stub
    ObservableList<OrgData> event=getAllFriends();
    OrgData Event=null;
    for (OrgData f:event) {
        if (f.getEmail().equals(email)){
            Event=f;
            break;
        }
    }
    return Event;
}

public void updateEvent(OrgData Event) {
    ObservableList<OrgData> Events=getAllFriends();
    for (int i=0; i<Events.size(); i++) {
        OrgData f=Events.get(i);
        if (f.getEmail().equals(Event.getEmail())){
            Events.set(i, Event);
        }
    }
    synToFile(Events);
}

public void deleteEvent(OrgData Event) {

    ObservableList<OrgData> Events=getAllFriends();

    OrgData delEvent=null;
    for (OrgData f:Events) {
        if (Event.getEmail().equals(f.getEmail())){
            delEvent=f;         
            break;
        }
    }
    if (delEvent!=null){
        Events.remove(delEvent);
        synToFile(Events);      
    }       

}

public boolean createFriend(OrgData Event) {
    boolean existing=false;
    ObservableList<OrgData> Events=getAllFriends();
    for (OrgData f:Events) {
        if (f.getEmail().equals(Event.getEmail())){
            existing=true;
            break;
        }
    }
    if (!existing) {
        Events.add(Event);
        synToFile(Events);
    }
    return !existing;
}

private void synToFile(ObservableList<OrgData> EventList) {
    if (EventList==null)
        return;

    try {
        FileWriter out = new FileWriter(dataFile);
        for (OrgData f: EventList) {
            out.append(f.toString()+"\n");
        }
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
2

There are 2 answers

3
fabian On BEST ANSWER

You need to reconsider storing the image just as Image object.

An Image object does not contain any information about the path (as you've already found out), since you can load it from any InputStream and there may not be a way to access the InputStream using a URL. (E.g. the image could be stored as a blob in a database making a query necessary to retrieve it...)

Store the url in a additional field when you open the file.

Furthermore I recommend using the Image class to load the image directly, since otherwise you create a BufferedImage and a Image object in memory which takes approx. twice the memory required for only one of those objects; the BufferedImage is available for garbage collection immediately after the method returns anyway...

private String imageUrl;

@FXML
private void handleUpload(ActionEvent t) {
    FileChooser fileChooser = new FileChooser();

    //Set extension filter


    //Show open file dialog
    File file = fileChooser.showOpenDialog(null);
    if (file != null) {
        try {
            imageUrl = file.toURI().toURL().toExternalForm();
            Image image = new Image(imageUrl);
            pic.setImage(image);
        } catch (MalformedURLException ex) {
            throw new IllegalStateException(ex);
        }
    }
}

@FXML
private void handleConfirmButtonAction(ActionEvent event) throws IOException {

    ...
    String url = imageUrl;
    ...
}

Note that if you add a default image in the fxml, you need to initialize imageUrl with this url.

0
AudioBubble On

The basic filechooser functions are

FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(null);

String imgAddress3;
if (file != null) {
    try {
        imgAddress3 = file.toURI().toURL().toExternalForm();
        Image image = new Image(imgAddress3);
        imageId.setImage(image);

        System.out.println(imgAddress3);
    } catch (MalformedURLException ex) {
        throw new IllegalStateException(ex);
    }
}

And for clarification, you can see this full project. https://github.com/ashrafulais/java_projects/tree/master/onCLickImageLoader