2012-06-14 71 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.