我想连续读取文本文件,并在读取某一行时更改我在画布上显示的框的颜色(文本文件将不断更新)。现在,我在画布上绘制了一个绿色正方形,在文本文件中绘制了三个“测试”行,当它到达文本文件的第三行时,我想将正方形更改为红色。
这是我的代码,来自两个文件(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());
}
}
}