Canvas class is a part of Java AWT. Canvas is a blank rectangular area where the user can draw or trap input from the user. Canvas class inherits the Component class.
Constructor of the Canvas class are :
- Canvas(): Creates a new blank canvas.
- Canvas(GraphicsConfiguration c): Creates a new canvas with a specified graphics configuration.
Commonly used Methods in Canvas Class
Method Explanation addNotify() Creates the peer of the canvas. createBufferStrategy(int n) Creates a new strategy for multi-buffering on this component. createBufferStrategy(int n, BufferCapabilities c) Creates a new strategy for multi-buffering on this component with the required buffer capabilities getBufferStrategy() Returns the BufferStrategy used by this component. paint(Graphics g) paints this component. update(Graphics g) updates this canvas.
Below programs illustrate the use of Canvas Class :
- Program 1: To create a canvas and paint the canvas.
- Program 2: To create a canvas and add mouse listener to the canvas(a circle of radius 5 will appear at the points where mouse are clicked or dragged on the canvas).
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.