Reputation: 41
I'm just getting started with JavaFX which i find pretty cool , so i m trying to implement the arraylist of an ToDListItem class into the listView of my FXML file
i've tried to add items in my arraylist which is todoitems , then set it all into the listView which has an id 'ToDoList' in my FXML file but it seems nothing happpend when the UI display
package sample;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import sample.ToDoList.ToDoItem;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.List;
public class Controller {
private List<ToDoItem> todoitems;
@FXML
private ListView ToDoList ;
public void intialize(){
ToDoItem item1= new ToDoItem("Going to Sea","Going to Sea with thamer and kais",
LocalDate.of(2020, Month.JUNE,16));
ToDoItem item2= new ToDoItem("JavaFx","Getting ready for real programming real world stuff",
LocalDate.of(2020, Month.JULY,14));
ToDoItem item3= new ToDoItem("Sleep & Chill","Going to Watch Youtube Later & Chill",
LocalDate.of(2020, Month.JANUARY,13));
todoitems= new ArrayList<>();
todoitems.add(item1);
todoitems.add(item2);
todoitems.add(item3);
ToDoList.getItems().setAll(todoitems);
ToDoList.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
}
}
FXML file.
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.control.ListView?>
<BorderPane fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml">
<left>
<ListView fx:id="ToDoList">
</ListView>
</left>
</BorderPane>
i didn't get any result when the UI displayed
Upvotes: 2
Views: 1813
Reputation: 1051
The method should be named initialize but not intialize. I would rather use javafx.fxml.Initializable to avoid misspelling issue.
This is not the recommended approach:
List<T> content = ...
getItems().setAll(content);
The issue with the approach shown above is that the content list is being copied into the items list.
Use:
ObservableList<T> content = ...
listView.setItems(content);
public class Controller {
private final List<ToDoItem> todoItems = FXCollections.observableArrayList();
@FXML
private ListView ToDoList ;
public void initialize() {
ToDoList.setItems(todoItems);
ToDoList.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
populate();
}
private void populate () {
todoItems.add(new ToDoItem("Going to Sea","Going to Sea with thamer and kais",
LocalDate.of(2020, Month.JUNE,16)));
todoItems.add(new ToDoItem("JavaFx","Getting ready for real programming real world stuff",
LocalDate.of(2020, Month.JULY,14)));
todoItems.add(new ToDoItem("Sleep & Chill","Going to Watch Youtube Later & Chill",
LocalDate.of(2020, Month.JANUARY,13)));
}
}
Make sure that the method ToDoItem.toString is overridden properly.
Upvotes: 3