简体   繁体   English

如何将文本文件中的行复制到 JComboBox 中?

[英]How can I copy lines from a text file into a JComboBox?

I'm trying to copy each line of a text file into a jcomboBox, but it displays only the first line of the text file in the jcomboBox...I don't understand why.我试图将文本文件的每一行复制到 jcomboBox 中,但它只显示 jcomboBox 中文本文件的第一行......我不明白为什么。 Can you please explain me what's wrong?你能解释一下有什么问题吗?

(...)
BufferedReader in;
    String read;

        try {
            in = new BufferedReader(new FileReader("D:/File.txt"));


            read = in.readLine();

            lines[w]=read;

             ++w;

            in.close();
        }catch(IOException e){
            System.out.println("There was a problem:" + e);
        }

    combo1 = new JComboBox(lines);

    combo1.setPreferredSize(new Dimension(100,20));
    combo1.setForeground(Color.blue);


    JPanel top = new JPanel();
    top.add(label);
    top.add(combo1);

    combo1.addActionListener(new ActionFichiers());

    container.add(top, BorderLayout.NORTH);
    this.setContentPane(container);
    this.setVisible(true);            
    }
(...)

That's because you read only the first line and close the file, consider:那是因为您只阅读了第一行并关闭了文件,请考虑:

     try {
        in = new BufferedReader(new FileReader("D:/File.txt"));
        while((read = in.readLine()) != null){
            lines[w]=read;
           ++w;
        }
        in.close();
    }catch(IOException e){
        System.out.println("There was a problem:" + e);
    }

Note: I assume the array lines is big enough注意:我假设数组lines足够大

You're only reading the first line of the file.您只是在读取文件的第一行。 So there can't be more in the JCombobox.所以在 JCombobox 中不能再有更多了。 You should use a while and read all lines till you reach the end.您应该使用一段时间并阅读所有行,直到到达结尾。

replace代替

read = in.readLine();

lines[w]=read;

with

while((read = in.readLine())!=null){
    lines[w++]=read;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM