Home java java. Canvas. JFrame

java. Canvas. JFrame

Author

Date

Category

The code below draws a line, a new one second.
How can I do to be added to the old one?
So I want to see through the conditionally twenty seconds – twenty lines.

1) you need to add values ​​to draw an array and redraw each time, as in the commented part,
2) Or you can use the old canvas and draw over it.

If the second option is how it can be done?

package draw;
Import javax.swing. *;
Import java.awt. *;
Public Class Test {
  Static Class Mycanvas Extends Canvas {
    // Conditional array with values
    // INT4 [] VALUES = NEW INT4 [];
    // Public Void AddValue (...) {//};
    Static int x1 = 10;
    static int x2 = 20;
    Public Void Paint (Graphics G) {
      G.Setcolor (Color.Black);
      // for (int4 Val: Values) {
      // G.Drawline (VAL [0], VAL [1], VAL [2], VAL [3])
      //}
      g.drawline (x1, x2, 200,200);
    }
  }
  Public Static Void Main (String [] Args) Throws InterruptedException {
    JFrame Frame = New JFrame ("Nameof");
    frame.setsize (200,200);
    Canvas canvas = new mycanvas ();
    Frame.add (canvas);
    frame.setvisible (TRUE);
    While (True) {
      Thread.sleep (1000);
      // canvas.addvalue (...);
      Mycanvas.x1 = (int) (math.random () * 100);
      Mycanvas.x2 = (int) (math.random () * 100);
      canvas.repaint ();
    }
  }
}

Answer 1

found an approximate solution, without declaring the collection. Use in the cycle:

canvas.getgraphics (). Drawline (x1, x2, y1, y2);

Only the result will not be saved if you call the .repaint () method
(for example, change the window size, which will automatically cause redrawing)

package draw;
Import javax.swing. *;
Import java.awt. *;
Import java.util.scanner;
Public Class Test {
  Static Class Mycanvas Extends Canvas {
    Public Void Paint (Graphics G) {
      G.Setcolor (Color.Black);
      g.drawoval ((int) (math.random () * 100), (int) (math.random () * 100), (int) (math.random () * 100), (int) (math.random () * 100));
    }
  }
  Public Static Void Main (String [] Args) {
    Mycanvas Canvas = New MycanVAS ();
    JFrame Frame = New JFrame ("Nameof");
    frame.setsize (200,200);
    Frame.add (canvas);
    frame.setvisible (TRUE);
    Scanner Scanner = New Scanner (System.in);
    While (scanner.hasnext ()) {
      canvas.getgraphics (). Drawline ((int) (math.random () * 100), (int) (math.random () * 100), 200,200);
      System.out.printLN ("---");
      Scanner.NextLine ();
    }
  }
}

In this example, to draw a new line, you need to enter any value from the keyboard into the console.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions