How do I populate JComboBox from a text file?

后端 未结 3 1750
忘掉有多难
忘掉有多难 2020-12-02 01:09

How do I populate a JComboBox from a text file?

3条回答
  •  孤街浪徒
    2020-12-02 02:01

    Very vague question. Are you saying you want one entry per line? If so you want to use something like a BufferedReader, read all the lines, save them as a String array. Create a new JComboBox passing in that String constructor.

    BufferedReader input = new BufferedReader(new FileReader(filePath));
    List strings = new ArrayList();
    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);
    

提交回复
热议问题