如何将arraylist实现到ListView中?

时间:2019-06-19 18:24:17

标签: java javafx

我刚开始使用JavaFX,我觉得它很酷,所以我试图将ToDListItem类的arraylist实现到FXML文件的listView中

我试图在arraylist中添加项目,这是todoitems,然后将其全部设置到FXML文件中具有id'ToDoList'的listView中,但是当显示UI时似乎没什么希望

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文件。

<?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>

显示界面时我没有得到任何结果

1 个答案:

答案 0 :(得分:2)

该方法应命名为初始化,而不是 int 初始化。我宁愿使用javafx.fxml.Initializable来避免拼写错误。

This is not the recommended approach

List<T> content = ...
getItems().setAll(content);

上述方法的问题在于内容列表已被复制到项目列表中。

使用:

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)));
    }
}

确保正确覆盖方法 ToDoItem.toString