2012-06-14 38 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

如何更新主方法內部的顏色? – kaptaincooke

回答

0

這裏有一種方法可以做到這一點沒有太大的改變你的代碼。

  1. 你叫ColorcurrentColorMyCanvas類創建一個局部變量。僅供參考,Java中的約定是讓類名以大寫字母開頭。
  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. 
相關問題