Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I Populate a ListView in JavaFX using Custom Objects?

I'm a bit new to Java, JavaFX, and programming in general, and I have an issue that is breaking my brain.

In most of the tutorials I have looked up regarding populating a ListView (Using an ObservableArrayList, more specifically) the simplest way to do it is to make it from an ObservableList of Strings, like so:

ObservableList<String> wordsList = FXCollections.observableArrayList("First word","Second word", "Third word", "Etc.");  ListView<String> listViewOfStrings = new ListView<>(wordsList); 

But I don't want to use Strings. I would like to use a custom object I made called Words:

ObservableList<Word> wordsList = FXCollections.observableArrayList(); wordsList.add(new Word("First Word", "Definition of First Word"); wordsList.add(new Word("Second Word", "Definition of Second Word"); wordsList.add(new Word("Third Word", "Definition of Third Word"); ListView<Word> listViewOfWords = new ListView<>(wordsList); 

Each Word object only has 2 properties: wordString (A string of the word), and definition (Another string that is the word's definition). I have getters and setters for both.

You can see where this is going- the code compiles and works, but when I display it in my application, rather than displaying the titles of every word in the ListView, it displays the Word object itself as a String!

Image showing my application and its ListView

My question here is, specifically, is there a simple way to rewrite this:

ListView<Word> listViewOfWords = new ListView<>(wordsList); 

In such a way that, rather than taking Words directly from wordsList, it accesses the wordString property in each Word of my observableArrayList?

Just to be clear, this isn't for android, and the list of words will be changed, saved, and loaded eventually, so I can't just make another array to hold the wordStrings. I have done a bit of research on the web and there seems to be a thing called 'Cell Factories', but it seems unnecessarily complicated for what seems to be such a simple problem, and as I stated before, I'm a bit of a newbie when it comes to programming.

Can anyone help? This is my first time here, so I'm sorry if I haven't included enough of my code or I've done something wrong.

like image 899
David Collins Avatar asked Apr 15 '16 21:04

David Collins


People also ask

What is TableView in Javafx?

The TableView class provides built-in capabilities to sort data in columns. Users can alter the order of data by clicking column headers. The first click enables the ascending sorting order, the second click enables descending sorting order, and the third click disables sorting. By default, no sorting is applied.

What is a display list Javafx?

A ListView displays a horizontal or vertical list of items from which the user may select, or with which the user may interact. A ListView is able to have its generic type set to represent the type of data in the backing model.


1 Answers

Solution Approach

I advise using a cell factory to solve this problem.

listViewOfWords.setCellFactory(param -> new ListCell<Word>() {     @Override     protected void updateItem(Word item, boolean empty) {         super.updateItem(item, empty);          if (empty || item == null || item.getWord() == null) {             setText(null);         } else {             setText(item.getWord());         }     } }); 

Sample Application

add image

import javafx.application.Application; import javafx.collections.*; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.stage.Stage;  public class CellFactories extends Application {         @Override     public void start(Stage stage) {         ObservableList<Word> wordsList = FXCollections.observableArrayList();         wordsList.add(new Word("First Word", "Definition of First Word"));         wordsList.add(new Word("Second Word", "Definition of Second Word"));         wordsList.add(new Word("Third Word", "Definition of Third Word"));         ListView<Word> listViewOfWords = new ListView<>(wordsList);         listViewOfWords.setCellFactory(param -> new ListCell<Word>() {             @Override             protected void updateItem(Word item, boolean empty) {                 super.updateItem(item, empty);                  if (empty || item == null || item.getWord() == null) {                     setText(null);                 } else {                     setText(item.getWord());                 }             }         });         stage.setScene(new Scene(listViewOfWords));         stage.show();     }      public static class Word {         private final String word;         private final String definition;          public Word(String word, String definition) {             this.word = word;             this.definition = definition;         }          public String getWord() {             return word;         }          public String getDefinition() {             return definition;         }     }      public static void main(String[] args) {         launch(args);     } } 

Implementation Notes

Although you could override toString in your Word class to provide a string representation of the word aimed at representation in your ListView, I would recommend providing a cell factory in the ListView for extraction of the view data from the word object and representation of it in your ListView. Using this approach you get separation of concerns as you don't tie a the graphical view of your Word object with it's textual toString method; so toString could continue to have different output (for example full information on Word fields with a word name and a description for debugging purposes). Also, a cell factory is more flexible as you can apply various graphical nodes to create a visual representation of your data beyond just a straight text string (if you wish to do that).

Also, as an aside, I recommend making your Word objects immutable objects, by removing their setters. If you really need to modify the word objects themselves, then the best way to handle that is to have exposed observable properties for the object fields. If you also want your UI to update as the observable properties of your objects change, then you need to make your list cells aware of the changes to the associated items, by listening for changes to them (which is quite a bit more complex in this case). Note that, the list containing the words is already observable and ListView will take care of handling changes to that list, but if you modified the word definition for instance within a displayed word object, then your list view wouldn't pick up changes to the definition without appropriate listener logic in the ListView cell factory.

like image 171
jewelsea Avatar answered Sep 23 '22 18:09

jewelsea