2016-04-01 3 views
0

Ich muss die ersten 10 Zeilen von der Verbindung fest zu address nehmen, damit ich sie in ein JLabel für GUI setzen kann. Ich habe mit line.split("\\s+") getrennt, aber ich kann nicht herausfinden, wie man die ersten 10 Zeilen in das Label verschiebt, da ich es innerhalb einer While-Schleife verwende.Wie man .txt Zeilen für eine JLabel verwendet

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"); 
       } 
+0

Haben Sie versucht, den Text in HTML zu verpacken? Für [Beispiel] (http://stackoverflow.com/questions/29550524/jlabel-with-multiple-lines-and-alignment-to-the-right/29551195#29551195) – MadProgrammer

+0

Ich bin mir nicht sicher, ob ich das Problem verstehe. Haben Sie versucht, die Zeichenfolge zu kombinieren, anstatt jede Zeile einer neuen Array-Position zuzuordnen? Versuchen Sie es auch mit 'JTextPane' oder' JTextArea'. –

Antwort

0

Meine Lösung ist das Array außerhalb der Schleife zu erstellen und die geteilten Linien hinzufügen.

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"); 
    } 
Verwandte Themen