0

Another newbie question from me. I have .mp3 files in a folder which I drag and drop into a ListView and I can display the name of the files in the ListView. How do I store the file path without displaying it so that I can click on the ListView entry and play the .mp3 file.

The only way I can think of doing this is to have 2 ListView controls in a StackPane and show the file names in one ListView and store the corresponding file path in the other ListView which will be hidden behind the ListView which displays the file names.

Does anybody know of a better way of doing this.

Thanks in advance of any help provided.

Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
Yastafari
  • 81
  • 6
  • For example, use a `ListView` and set the cell factory so that the cells display only the file name (e.g. `Path#getFileName()`); you'll maintain a reference to the actual, absolute `Path` but the UI will only show the file name. If you're not comfortable with `Path` there's also `java.io.File`, though I find the former to be a much better API. – Slaw Dec 31 '19 at 23:19
  • 3
    What makes you think you need another `ListView`? Even if you could not put all the required info in `ListView` items as described by Slaw, why use a GUI element that you never want to display just for storing data, if a `List` would do the trick too? – fabian Jan 01 '20 at 02:30
  • fabian: It was just a thought. A hack if you like. I am only just finding my feet with java. I have only been coding in it for a little under 2 months. – Yastafari Jan 02 '20 at 10:35
  • Slaw: Thanks for that. You were right. That was exactly what I needed. – Yastafari Jan 05 '20 at 12:14

1 Answers1

1

You can add files to the ListView and show only their names:

ListView<File> filesList = new ListView<File>();

// Showing only the filename in the list
filesList.setCellFactory(new Callback<ListView<File>, ListCell<File>>() {
    public ListCell<File> call(ListView<File> param) {
        return new ListCell<File>() {
            @Override
            protected void updateItem(File item, boolean empty) {
                super.updateItem(item, empty);
                setText(item == null || empty ? null : item.getName());
            }
        };
    }
});

// Playing when a file is selected
filesList.getSelectionModel().selectedItemProperty().addListener((observable, oldFile, newFile) -> {
    stopPlaying(oldFile);
    play(newFile);
});
Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36