【问题标题】:How do I populate JComboBox from a text file?如何从文本文件中填充 JComboBox?
【发布时间】:2015-10-22 16:19:52
【问题描述】:

如何从文本文件中填充JComboBox

【问题讨论】:

    标签: java text-files jcombobox populate


    【解决方案1】:

    非常模糊的问题。你是说你想要每行一个条目吗?如果是这样,您想使用类似 BufferedReader 的东西,读取所有行,将它们保存为字符串数组。创建一个传入该 String 构造函数的新 JComboBox。

    BufferedReader input = new BufferedReader(new FileReader(filePath));
    List<String> strings = new ArrayList<String>();
    try {
      String line = null;
      while (( line = input.readLine()) != null){
        strings.add(line);
      }
    }
    
    catch (FileNotFoundException e) {
        System.err.println("Error, file " + filePath + " didn't exist.");
    }
    finally {
        input.close();
    }
    
    String[] lineArray = strings.toArray(new String[]{});
    
    JComboBox comboBox = new JComboBox(lineArray);
    

    【讨论】:

      【解决方案2】:

      这是一个example,它读取属性文件以获取键(用于组合)和值(用于文本区域)。请参阅source 中的enum Rule

      【讨论】:

        【解决方案3】:

        将您的要求分解为单独的步骤,代码如下:

        1) 从文件中读取一行数据 2) 使用JComboBox addItem(...) 方法将数据添加到组合框

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-27
          • 2019-08-14
          • 2014-10-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多