2012-06-14 3 views
0

텍스트 파일에서 계속 읽으며 특정 줄을 읽을 때 캔버스에 표시된 상자의 색을 변경하고 싶습니다 (텍스트 파일이 계속 업데이트 될 예정 임)). 지금은 캔버스에 그린 사각형과 텍스트 파일에있는 세 개의 "테스트"라인이 있으며 텍스트 파일의 세 번째 줄에 도달하면 사각형을 빨간색으로 변경하고 싶습니다.파일에서 지속적으로 읽은 다음 작업 수행

두 파일 (myCanvas.java 및 myFileReader.java)의 코드입니다. 올바른 방향의 모든 점을 크게 높이 평가합니다.

public class myCanvas extends Canvas{ 

    public myCanvas(){ 
    } 

    public void paint(Graphics graphics){ 
     graphics.setColor(Color.green); 
     graphics.fillRect(10, 10, 100, 100); 
     graphics.drawRect(10,10,100,100); 
    } 

    public static void main(String[] args){ 
     myCanvas canvas = new myCanvas(); 
     JFrame frame = new JFrame("Live GUI"); 
     frame.setSize(400, 400); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(canvas); 
     frame.setVisible(true); 
     myFileReader read = new myFileReader(); 
     read.readFromFile(); 
     if(myFileReader.strLine == "This is the third line."){ 
     //change color 
     } 

} 



public class myFileReader{ 
    public static String strLine; 

public void readFromFile() 
{ 
    try{ 
     FileInputStream fstream = new FileInputStream(System.getProperty("user.dir")+"\\sample.txt"); 
     DataInputStream in = new DataInputStream(fstream); 
     BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
     while (true){ 
      strLine = br.readLine(); 
      if(strLine == null) { 
       Thread.sleep(1000); 
      } 
     } 
     } 
    catch (Exception ex){ 
     System.err.println("Error: " + ex.getMessage()); 
    } 
    } 
} 
+0

무엇이 문제입니까? – user845279

+0

main 메서드 내부에서 색을 어떻게 업데이트합니까? – kaptaincooke

답변

0

을하려고 할 때 다음은 코드를 많이 변경하지 않고 그것을 할 수있는 방법입니다.

  1. 유형 ColorcurrentColor라는 MyCanvas 클래스의 로컬 변수를 만듭니다. 참고로, 자바 대회는 클래스 이름을 대문자로 시작하는 것입니다.
  2. paint() 메서드를 업데이트하여 고정 녹색 값 대신 사각형의 색을 새 변수 currentColor으로 설정합니다.
  3. 주 방법에서는 canvas.currentColor = <new color here>;canvas.repaint()을 사용할 수 있습니다. repaint() 함수 호출은 캔버스를 지우고 paint() 함수를 사용하여 다시 그립니다.

귀하의 FileReader은 지속적으로 수정되는 파일과 잘 어울리지 않을 것이라고 생각합니다.

+0

신난다, 그것이 내가 찾고 있었던 정확하게 것이다! – kaptaincooke

+0

@ user1442737 아주 좋습니다. 제발 [수락] (http://meta.stackexchange.com/q/5234) 대답. – user845279

0

단순히 카운터를 추가하고 줄을 읽을 때마다 카운터를 늘리십시오. 카운터가 세 번째 줄의 사용에 도달 if 문이 작업을 수행하는 경우

0

1.Use BreakIterator class, with its static method getLineInstance(), 
    this will help you identify every line in the file. 

2. Create an HashMap with the colour as Key, and its RGB as Value. 

3. Parse every word in the line, which is obtained from 
    BreakIterator.getLineInstance(). 

4. Compare it with the Key in the HashMap, 
    if the word in the line happens to match the Key in 
    the HashMap, then colour the box with the Value of the Key. 
관련 문제