我在 Scene Builder 中创建了一个 ComboBox,我想用文本文件(例如 Text.txt)中的数据填充他:
公共类 ToDoListController 实现 Initializable {
@FXML
private ComboBox<?> eventsSelector;
这该怎么做?
非常感谢你!
两种解决方法:1。
@FXML 私有组合框事件选择器;
@Override
public void initialize(URL location, ResourceBundle resources) {
List<String> myList;
try {
myList = Files.lines(Paths.get("path of my text file")).collect(Collectors.toList());
eventsSelector.setItems(FXCollections.observableArrayList(myList));
} catch (IOException e) {
System.out.println("Don t find file");
}
2.
//Read items from txt File
try {
BufferedReader br = new BufferedReader(new
FileReader("path of my text file"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
//Add Item
eventsSelector.getItems().add(line);
sb.append(line);
line = br.readLine();
}
br.close();
} catch (IOException e) {
System.out.println("Don t find file");
}
既然你想从添加内容.txt
文件中的项目ComboBox
是String
如此的,你可以改成这样:
@FXML
private ComboBox<String> eventsSelector;
然后,您需要一个要添加到 的元素列表ComboBox<String>
,然后您可以简单地添加它们:
List<String> myList = Files.lines(path).collect(Collectors.toList());
comboBox.setItems(FXCollections.observableArrayList(myList));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句