【问题标题】:How to add a text file contents into combo box where text file contains spaces?如何将文本文件内容添加到文本文件包含空格的组合框中?
【发布时间】:2020-04-13 23:31:13
【问题描述】:

我想在 Swing 组合框中添加文本文件内容。

我需要每一行作为组合框中的每个元素。但该文件包含单词之间的空格。所以它是通过单独的元素在空白上分割。

我使用了DefaultCombBoxModelmodel.addElement

我尝试了以下方法,但它不起作用:

String.replace(" ", "_")

【问题讨论】:

  • 请粘贴您的代码。
  • 如果您使用 Scanner 读取文件,则不要使用 Scanner#next() 方法。将 Scanner#nextLine() 方法与 Scanner#hasNextLine() 结合使用:String line; jComboBox1.removeAllItems(); while (scan.hasNextLine()) { line = scan.nextLine(); if (line.trim().equals("")) { continue; } jComboBox1.addItem(line); }.
  • @SurajGautam “请粘贴您的代码” 不,请不要这样做。相反,准备并将minimal reproducible example 发布为edit。 Suraj,提示:请注意,评论中的 [mre] 会自动扩展为 minimal reproducible example
  • 哦,对 OP 来说:在 String 中硬编码一些“行”,这样代码就可以重现问题,而无需 I/O 或文本文件等外部资源。
  • “我需要每一行作为组合框中的每个元素。” 所以逐行读取输入(例如使用BufferedReader.readLine())并将每一行直接放入组合盒子模型。 AFAIU 类似/相同可以使用上面@DevilsHnd 引用的Scanner 来完成。

标签: java string swing jcombobox text-parsing


【解决方案1】:

您可以使用以下解决方案:

BufferedReader reader = new BufferedReader(new FileReader("Filepath"));
        String line = null;
        StringBuilder stringBuilder = new StringBuilder();
        String ls = System.getProperty("line.separator");
        List<String> comboElmnts = new ArrayList<String>();
        try {
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append(ls);
                comboElmnts.add(line);
            }
            for (String lineItem : comboElmnts) {
                System.out.println(lineItem);
            }

        } finally {
            reader.close();
        }

您可以使用 comboElmts 列表项作为您的组合项。

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 2010-09-28
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多