【问题标题】:How to add data from a text file to ComboBox in JavaFX?如何将文本文件中的数据添加到 JavaFX 中的 ComboBox?
【发布时间】:2017-06-08 11:01:42
【问题描述】:

我在 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");

    }

【问题讨论】:

  • 我的回答对你有用吗??或者你还需要什么?
  • 谢谢!我明天试试。我与您保持联系!
  • 那太好了。如果您有问题,请写信给我。

标签: file text javafx combobox


【解决方案1】:

由于您想从.txt 文件中添加内容,因此ComboBox 中的项目为Strings,因此您可以更改为:

@FXML
private ComboBox<String> eventsSelector;

然后你需要一个你想添加到ComboBox&lt;String&gt;的元素列表,然后你可以简单地添加它们:

List<String> myList = Files.lines(path).collect(Collectors.toList());
comboBox.setItems(FXCollections.observableArrayList(myList));

【讨论】:

【解决方案2】:

我为你写了一些代码,这应该对你有用:

public class YourController {
//Combobox
@FXML
ComboBox<String> combobx;

//Initialize FXML
@FXML
public void initialize() throws IOException {
    //Read items from txt File
    BufferedReader br = new BufferedReader(new FileReader("/items.txt"));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            //Add Item
            combobx.getItems().add(line);

            sb.append(line);
            line = br.readLine();
        }
    } finally {
        br.close();
    }

    //Default Selection first item
    combobx.getSelectionModel().select(0);
}
}

在这种情况下,txt 文件必须位于项目的根目录中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多