【问题标题】:How to add items to a JComboBox from an External File?如何将项目从外部文件添加到 JComboBox?
【发布时间】:2011-03-06 20:02:10
【问题描述】:

在从外部文件向 Java 中的 JComboBox 添加项目时,我需要一些帮助。

这是我目前的代码:

 //Loading the Names:

        File Names_File = new File("Data" + File.separator + "Names.txt");
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;

        String str_Data = ""; //For storing the input from the file.

        try
        {
            fis = new FileInputStream(Names_File);

            // Here BufferedInputStream is added for fast reading.
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);


            str_Data = dis.readLine(); //Reading the line from the file.

            StringTokenizer st = new StringTokenizer(str_Data); //Tokenizing the line.

            //The below line adds only one item. The objective is adding all the items.

            //*** Requesting help here ***

            cmb_Name.addItem(st.nextToken("|"));

            //*** Requesting help here ***

            // Disposing and closing all the resources after using them.
            fis.close();
            bis.close();
            dis.close();
        }

        catch (FileNotFoundException e)
        {
            System.err.println("Error: File not found!");
            JOptionPane.showMessageDialog(null, "Error: File not found!", "Error Message",
                                          JOptionPane.ERROR_MESSAGE);
        }

        catch (IOException e)
        {
            System.err.println("Error: Unable to read from file!");
            JOptionPane.showMessageDialog(null, "Error: Unable to read from file!", "Error Message",
                                          JOptionPane.ERROR_MESSAGE);
        }

主要是我的外部文件格式如下:

詹姆斯|罗伯特|爱丽丝

名称由 "|" 符号分隔。

我上面的代码在这个例子中只添加了一个元素,即 ("James")。我需要添加所有三个可能在一个循环或什么的。这个想法是我不确定我的外部文件中有多少个名字。因此,使用简单的计数器将无济于事。

非常感谢任何建议!

提前感谢您的帮助

【问题讨论】:

    标签: java file-io io text-processing jcombobox


    【解决方案1】:

    试试这个:

       StringTokenizer st = new StringTokenizer(str_Data); //Tokenizing the line.
    
       while(st.hasMoreTokens()) {
            cmb_Name.addItem(st.nextToken("|"));
       }
    

    【讨论】:

      猜你喜欢
      • 2015-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 2016-10-17
      • 2011-05-26
      • 2011-01-23
      • 2023-03-18
      相关资源
      最近更新 更多