0

テキストファイルから継続的に読み取り、特定の行が読み取られたときにキャンバスに表示されているボックスの色を変更したい(テキストファイルは常に更新されます)。現在、キャンバスに緑の四角が描かれ、テキスト ファイルに 3 つの「テスト」行があり、テキスト ファイルの 3 行目に到達したら、四角を赤に変更したいと考えています。

2 つのファイル (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());
    }
    }
}
4

3 に答える 3

0

カウンターを追加して、行を読み取るたびにインクリメントするだけです。カウンターが 3 行目に達したら、if ステートメントを使用してタスクを実行します

于 2012-06-14T17:31:03.180 に答える
0

コードをあまり変更せずに実行できる方法を次に示します。

  1. typeMyCanvasという名前のクラスにローカル変数を作成します。参考までに、Java の規則では、クラス名は大文字で始めます。currentColorColor
  2. メソッドを更新してpaint()、四角形の色をcurrentColor静的な緑の値ではなく、新しい変数 に設定します。
  3. あなたの主な方法では、あなたはすることができますcanvas.currentColor = <new color here>;そして、canvas.repaint(). repaint()関数呼び出しはキャンバスを消去し、関数を使用して再描画しますpaint()

FileReaderただし、常に変更されているファイルではうまく機能するとは思いません。

于 2012-06-14T19:41:32.133 に答える
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.
于 2012-06-14T18:09:24.703 に答える