如何使用.txt行作为JLabel

时间:2016-04-01 03:29:47

标签: java swing jlabel

我需要从固定到address的链接中获取前10行,这样我就可以将它们放入JLabel for GUI中。我用line.split("\\s+")分隔但我无法弄清楚如何将前10行移动到Label中,因为我在while循环中使用它。

try{   
                String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
                URL pageLocation = new URL(address);
                Scanner in = new Scanner (pageLocation.openStream()); 
                String line = ""; //intialize
                int i = 0; 

                while(i < 10){ //add limit for 10
                   line = in.nextLine(); //take line
                   String[] content = line.split("\\s+"); //seperate by multiple spaces
                   i++; //count another country
                }

                }
                catch (IOException exception){
                    System.out.println("File not Found");
                }

1 个答案:

答案 0 :(得分:0)

我的解决方案是在循环外创建数组并将分割线添加到它。

    try {
        String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
        URL pageLocation = new URL(address);
        Scanner in = new Scanner(pageLocation.openStream());
        String line = ""; // intialize
        int i = 0;
        String[] panelContent = new String[10];
        while (i < 10) { // add limit for 10
            line = in.nextLine(); // take line
            // seperate by multiple spaces, but must be more than one
            // because some countrys have composed names like United States
            String lineContent[] = line.split("\\s\\s+");
            panelContent[i] = String.format("%s %s %s", lineContent[0], lineContent[1], lineContent[2]);
            i++; // count another country
        }
        // Here you have de content to populate de JLabel
        System.out.println(Arrays.toString(panelContent));

    } catch (IOException exception) {
        System.out.println("File not Found");
    }