【问题标题】:How to set items of a TableView in a different controller class in JavaFX?如何在 JavaFX 的不同控制器类中设置 TableView 的项目?
【发布时间】:2015-08-05 16:09:35
【问题描述】:

我有两个 fxml 文件,其中包含两个控制器类 MainController 和 PlaylistController。每个类都有一个 TableView,分别是 tablenTable

table 显示为 TabPane 上的默认选项卡

nTable 应用于使用按钮创建的新选项卡。

我想要的是能够在默认表中选择项目,并在一个操作中将它们添加到新标签上的新表中(我可以使用两个按钮来完成,其中一个在新标签之后被单击被建造)。

我猜我需要确保程序在设置项目之前等待新标签创建,但我不知道该怎么做。

这是我正在使用的方法:

@FXML
PlaylistController pc;    

public static ObservableList<Track> newTracklist = FXCollections.observableArrayList();

public void addToNewPlaylist(){
    newTracklist.clear();
    newTracklist.addAll(table.getSelectionModel().getSelectedItems());

    Tab nTab = new Tab();

    FXMLLoader nLoader = new FXMLLoader(getClass().getResource("/fxml/fxPlaylist.fxml"));
    try {
        Parent nRoot = nLoader.load();
        nTab.setContent(nRoot);     
    } catch (IOException e) {
        e.printStackTrace();
    }
    tabPane.getTabs().add(nTab);
    nTab.isClosable();
    pc.nTable.setItems(newTracklist);
}

【问题讨论】:

    标签: java javafx tabs tableview


    【解决方案1】:

    除非您定义一个常量或类似的东西,否则static 字段在控制器中没有位置。

    在您的PlaylistController 中定义一个方法以获取Tracks 的列表以显示在其表中:

    public class PlaylistController {
    
        @FXML
        private TableView<Track> nTable ;
    
        // ...
    
        public void setTracks(List<Track> tracks) {
            nTable.getItems().setAll(tracks);
        }
    
        // ...
    }
    

    然后在加载 FXML 时调用它:

    public void addToNewPlaylist(){
    
        Tab nTab = new Tab();
    
        FXMLLoader nLoader = new FXMLLoader(getClass().getResource("/fxml/fxPlaylist.fxml"));
        try {
            Parent nRoot = nLoader.load();
            PlaylistController controller = nLoader.getController();
            controller.setTracks(table.getSelectionModel().getSelectedItems());
            nTab.setContent(nRoot);     
        } catch (IOException e) {
            e.printStackTrace();
        }
        tabPane.getTabs().add(nTab);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2015-08-07
      • 1970-01-01
      • 2017-03-11
      • 2023-04-05
      相关资源
      最近更新 更多