2011-01-31 2 views
0

내 highscore.txt 파일을 읽으므로 내 게임의 최고 기록 메뉴에 표시 할 수 있습니다. 내 highscore.txt의 내용은 SCORE 및 NAME입니다. 예 :Java 파일 읽기 문제

150 John 
    100 Charice 
    10 May 

그래서 텍스트 영역에서 파일을 읽으려면 다음 코드를 작성하지만 파일을 읽을 수는 없습니다. 내 코드는 다음과 같습니다 :

public HighScores(JFrame owner) { 
     super(owner, true); 
     initComponents(); 
     setSize(500, 500); 
     setLocation(300, 120); 
     getContentPane().setBackground(Color.getHSBColor(204, 204, 255)); 

     File fIn = new File("highscores.txt"); 
     if (!fIn.exists()) { 
      jTextArea1.setText("No high scores recorded!"); 
     } else { 
      ArrayList v = new ArrayList(); 
      try { 
       BufferedReader br = new BufferedReader(new FileReader(fIn)); 
       String s = br.readLine(); 
       while (s != null) { 
        s = s.substring(2); 
        v.add(s); 
        s = br.readLine(); 
       } 

       br.close(); 
      } catch (IOException ioe) { 
       JOptionPane.showMessageDialog(null, "Couldn't read high scores file"); 
      } 

      // list to display high scores 
      JList jlScores = new JList(v); //there's a problem here. I don't know why 
      jTextArea1.add(jlScores, BorderLayout.CENTER); 

     } 
    } 

내가 뭘 잘못하고 있니? 어떻게하면이 작업을 할 수 있습니까>. 당신은 도움을 주시면 감사하겠습니다. 미리 감사드립니다.

+0

당신은 당신이 당신의 파일에서 텍스트의 줄을 구문 분석하는 방법을 살펴 할 수 있습니다. 's = s.substring (2);'는 문자열에서 처음 두 문자를 삭제합니다. 대신 토큰 배열을 얻기 위해 문자열을 공백 문자로 분할하고자 할 수 있습니다. 이 경우 [0]은 점수가되고 [1]은 이름이됩니다. – Qwerky

+0

@Qwerky 어떻게 분할 할 수 있습니까? 감사합니다. – newbie

+0

http://download.oracle.com/javase/6/docs/api/java/lang/String.html의 String에 대한 API 문서를 확인하십시오. 'split'이라는 메소드가 있습니다. – Qwerky

답변

3

파일의 내용을 ArrayList v으로 읽는 중입니다.이 내용을 채운 후에는 아무 것도하지 않습니다.

점수를 표시하는 코드에 jTextArea1에 빈 JList을 추가하는 중입니다. ArrayList v의 내용으로 JList을 채우려는 것일 수 있습니다.

+0

하지만 어떻게 할 수 있습니까? 고맙습니다. – newbie

1

ArrayList 개체로 JList를 초기화하려고합니다.

JList jlScores = new JList(v); 

나는 one with Vector가, ArrayList의 아무 JList의 생성자가 없기 때문에이 문제가 될 수 있다고 생각. ArrayList에 소요 생성자가 없다

1
JList jlScores = new JList(v); //there's a problem here. I don't know why 

javadoc의 생성자를 보라. 대신 arraylist를 배열로 변환 한 다음 생성자에서 사용하십시오.

arraylist를 배열로 변환하는 방법에 관해서는, 숙제이므로 운동으로 남겨 두겠다. 약간의 인터넷 검색은 아무런 문제가 없다. JList Tutorial에서 설명한 바와 같이 다음과 같이

1

, 나는 JList의를 채울의 ListModel를 사용하는 것이 좋습니다 것 :

//create a model 
DefaultListModel listModel = new DefaultListModel(); 

//now read your file and add each score to the model like this: 
listModel.addElement(score); 

//after you have read your file, set the model into the JList 
JList list = new JList(listModel);