如何在JavaFX中的其他控制器类中设置TableView的项目? [英] How to set items of a TableView in a different controller class in JavaFX?
问题描述
我有两个带有两个控制器类MainController和PlaylistController的fxml文件.每个类分别具有一个TableView,table
和nTable
.
I have two fxml files with two controller classes MainController and PlaylistController. Each class has a TableView, table
and nTable
respectively.
table
在TabPane上显示为默认选项卡
table
is displayed as the default tab on a TabPane
nTable
属于使用按钮创建的新标签.
nTable
aplies to a new tab created with a button.
我想要的是能够在一个默认动作中选择默认表中的项目并将其添加到新选项卡上的新表中(我可以使用两个按钮来完成操作,其中一个在新选项卡之后被单击被建造).
What I want is to be able to select items in the default table and add them to a new table on a new tab in a single action (I can do it using two buttons, one of them being clicked after the new tab is created).
我猜我需要确保程序在设置项目之前等待创建新选项卡,但是我不知道该怎么做.
I'm guessing I need to make sure the program waits for the new tab to be created before setting the items but I don't know how to do that.
这是我正在使用的方法:
This is the method I'm using:
@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);
}
推荐答案
除非您要定义常量或类似内容,否则static
字段在控制器中将没有位置.
Unless you are defining a constant, or something similar, static
fields have no place in a controller.
在PlaylistController
中定义一个方法,以获取Track
的列表以在其表中显示:
Define a method in your PlaylistController
to take a list of Track
s for display in its table:
public class PlaylistController {
@FXML
private TableView<Track> nTable ;
// ...
public void setTracks(List<Track> tracks) {
nTable.getItems().setAll(tracks);
}
// ...
}
然后在加载FXML时调用它:
Then just call it when you load the 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);
}
这篇关于如何在JavaFX中的其他控制器类中设置TableView的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!