用文本文件填充JCombobox [英] Populating JCombobox with a text file

查看:106
本文介绍了用文本文件填充JCombobox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何从文本文件中填充JComboBox?

我是Java新手,只有2个月的经验。任何人都可以帮我用一个包含5行的文本文件填充 JComboBox 吗?我查看了Google上的代码,但我一直在收到错误。

I am new to programming Java with only 2 months of experience. Can anyone help me to populate a JComboBox with a text file, consisting of 5 lines? I have looked at code on Google, but I keep getting errors.

推荐答案

private void populate() {
    String[] lines;
    lines = readFile();

    jComboBox1.removeAllItems();

    for (String str : lines) {
       jComboBox1.addItem(str);
    }
}

这是readFile()。 来自此网站

Here is readFile(). From this site

private String[] readFile() {
  ArrayList<String> arr = new ArrayList<>();
  try {
     FileInputStream fstream = new FileInputStream("textfile.txt");
     BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
     String strLine;
     while ((strLine = br.readLine()) != null) {
        arr.add(strLine);
     }
     in.close();
  } catch (Exception e) {
  }
  return arr.toArray(new String[arr.size()]);
}

这篇关于用文本文件填充JCombobox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆