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

时间:2022-04-12 23:15:57

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. Can you please explain me what's wrong?

我正在尝试将文本文件的每一行复制到jcomboBox中,但它只显示jcomboBox中文本文件的第一行...我不明白为什么。你能解释一下我有什么问题吗?

(...)
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);            
    }
(...)

3 个解决方案

#1


5  

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

注意:我假设阵列线足够大

#2


4  

You're only reading the first line of the file. So there can't be more in the JCombobox. You should use a while and read all lines till you reach the end.

你只是在读文件的第一行。所以在JCombobox中不可能有更多。您应该使用一段时间并阅读所有行,直到结束。

#3


4  

replace

更换

read = in.readLine();

lines[w]=read;

with

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

#1


5  

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

注意:我假设阵列线足够大

#2


4  

You're only reading the first line of the file. So there can't be more in the JCombobox. You should use a while and read all lines till you reach the end.

你只是在读文件的第一行。所以在JCombobox中不可能有更多。您应该使用一段时间并阅读所有行,直到结束。

#3


4  

replace

更换

read = in.readLine();

lines[w]=read;

with

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