Open In App

How to Place an Image in AWT in Java

AWT stands For Abstract Window Tool Kit. In the AWT we could place the image in the frame using the ToolKit class and MediaTracker class in the java.awt.* package. We can display image formats like GIF or JPG images in the AWT Frame with the help of the following steps in Java.

Loading the image into the object

For loading images into the object we can use the syntax mentioned below.



Syntax:

Image img = ToolKit.getDefaultToolKit().getImage("Path")

Now after the image is completely loaded into the Image class Object with the help of the Graphics class we use the below method to place the image in the frame



Graphics.drawImage(Image Object,int x_coordinate,int y_coordinate,int width,int height,Observer null)

To display an image on the title bar use

Frame.setIconImage(Image Object) . 

Program to add an image in AWT

Here we call the getImage() Method with the help of ToolKit.getDefaultToolKit() object. But the main thing is that it takes some time to load the image into the object.

Now, JVM will be waiting until the image is completely loaded with the help of MediaTracker.waitForId(int id). The image should be in the same folder or mention the path of the Image.

Below is the implementation of Add Image in AWT:




// Java Program to implement
// Image in AWT in Java
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
  
public class GFG extends Frame{
    static Image img;
  
    GFG() {
        
        //Using ToolKit image getImage to get the Image
        img = Toolkit.getDefaultToolkit().getImage("Geeks.png");
        
        //Mention the path or save the image in the same folder
        MediaTracker track = new MediaTracker(this);
        
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        
        //Use a unique id for the image object
        track.addImage(img,0);
        
        try {
            track.waitForID(0);
        }
        catch(InterruptedException ae){ 
        }
        //The JVM waits until the image is completely loaded
  
    }
    
    public void paint(Graphics g){
        g.drawImage(img,150,200,200,200,null);
    }
    
    public  static void main(String args[]){
        
        GFG g = new GFG();
        
        g.setTitle("Geeks For Geeks");
        g.setSize(500,500);
        
        //Setting the IconImage in the Frame
        g.setIconImage(img);
        g.setVisible(true);
        
    }
    
}

Output:

.

Here we can also observe that the image icon has also changed in the frame

The Frame.setIconImage() have also the same image on the Title Bar

This is about placing an image in the AWT Frame on Java and setting the icon image on the title bar in the AWT Frame.


Article Tags :