2011-12-05 30 views
0

テキストファイルの内容をjListにロードするにはどうすればいいですか? 私はコンソールのファイルの内容を印刷することができました。 私はRead()関数を呼び出して、ファイルの内容を行ごとに読み込み、Load()関数はjListに内容を表示する必要があります。jListにファイル内容を書き込む

負荷のためのコード:

public void Load() 
{ 

    Read(); 
    File archive = null; 
    FileReader fr = null; 
    BufferedReader br = null; 

    try { 
     archive = new File ("Cars.txt"); 
     fr = new FileReader (archive); 
     br = new BufferedReader(fr); 
     Vector<String> lines = new Vector<String>(); 

     String line; 
     while((line=br.readLine())!=null) { 
      System.out.println(line); 
      lines.add(line); 
     } 
    } catch(Exception e) { 
     e.printStackTrace(); 
    } finally { 
     try{ 
      if(null != fr) { 
       fr.close(); 
      } 
     } catch (Exception e2) { 
      e2.printStackTrace(); 
     } 
    } 
    } 

読み取りのためのコード:あなたはあなたができるデータの各行を読んだときに次に

DefaultListModel model = new DefaultListModel(); 
JList list = new JList(model); 

public void Read() 
{ 
    String name , type , distance, time; 
    File file=new File("Cars.txt"); 
    FileInputStream fis=null; 
    BufferedInputStream bis=null; 
    DataInputStream dis=null; 

    try { 
     fis = new FileInputStream(file); 
     bis = new BufferedInputStream(fis); 
     dis = new DataInputStream(bis); 

     while (dis.available() != 0) 
     { 
      String x=dis.readLine(); 
      int k1=x.length(); 
      char []m=x.toCharArray(); 
      int y1=0, y2=0, z=1; 
      for(int i=1;i<k1;i++) 
       if(m[i]==' ' && z==1) 
       { 
        y1=i; 
        z++; 
       } 
       else if(z==2 && m[i]==' ') {y2=i; z++; } 

      k1-=y2; 
      name=x.copyValueOf(x.toCharArray(), 0, y1); 
      type=x.copyValueOf(x.toCharArray(), 0, y2); 
      distance=x.copyValueOf(x.toCharArray(), y1+1, y2-y1-1); 
      time=x.copyValueOf(x.toCharArray(), y2+1, k1-1); 
      int d=Nr(distance); 
      int t=Nr(time); 
      // System.out.println(name + " " +q + " " + n); 

      list.Add(name, type , d, t); 
     } 

     fis.close(); 
     bis.close(); 
     dis.close(); 

    } 
    catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
} 
+0

[TXTファイルをJListに読み込む方法は?](http://stackoverflow.com/questions/5930353/how-to-load-a-txt-file-into-a-jlist) –

答えて

4

のようなリストを作成します。使用:

model.addElement(...); 
+0

It jlistには何も書き込まれません。 –

+1

問題を示す[SSCCE](http://www.sscce.org)を作成(および投稿)してください。これはJList(スクロールペイン内)とJButtonを持つフレームを作成します。ボタンをクリックすると、JListのモデルにいくつかの項目を手動で追加します。この作業が完了したら、コードを変更してファイルを読み込み、各行をモデルに追加します。 – camickr

+0

私はいくつかのOracle Javaチュートリアルを使用して何とかそれを管理してきました。君たちありがとう。 –

関連する問題