Canvas in Java AWT


The Canvas class controls and represents a blank rectangular area where the application can draw or trap input events from the user. It inherits the Component class.

Constructor Used for
Canvas() Creates a new blank canvas.
Canvas(GraphicsConfiguration c) Creates a new canvas with a specified graphics configuration.

This Java AWT program demonstrates the use of the Canvas component, which is used to create a blank rectangular area to draw graphics or to display images.

The program creates a new Frame named MyApp and sets its size and layout to null (i.e., absolute positioning). It then creates an instance of MyCanvas, which is a class that extends the Canvas component. The constructor of MyCanvas sets its background color to gray and its size to 300x200 pixels.

The paint method of MyCanvas is overridden to draw a red oval shape on the canvas using the Graphics object passed as a parameter. The fillOval method of the Graphics object is used to draw the oval shape. The MyCanvas object is added to the Frame using the add method.

Finally, the program adds a WindowListener to the Frame to exit the program when the window is closed. The main method creates an instance of MyApp to display the GUI. When the MyCanvas component is displayed, the paint method is automatically called to draw the red oval shape.

Source Code

package awtDemo;
 
import java.awt.*;
import java.awt.event.*;
 
//Canvas in Java AWT
 
class MyCanvas extends Canvas    
{    
    public MyCanvas() {    
        setBackground (Color.GRAY);    
        setSize(300, 200);    
     }     
  public void paint(Graphics g)    
  {    
    g.setColor(Color.red);    
    g.fillOval(75, 75, 150, 75);    
  }    
}  
 
 
class MyApp extends Frame{
 
	public MyApp() {
		super("Tutor Joes");
		setSize(1000, 600);// w,h
		setLayout(null);
		setVisible(true);
 
		add(new MyCanvas());
 
 
 
		// Close Button Code
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				System.exit(0);
			}
		});
	}
 
}
 
public class app {
	public static void main(String[] args) {
		MyApp frm = new MyApp();
	}
 
}
 
To download raw file Click Here

Output

Java AWT


Basic Programs