Displaying Image

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Displaying image in swing:

 

For displaying image, we can use the method drawImage() of Graphics class.

Syntax of drawImage() method:

  1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.

 

 

Example of displaying image in swing:

Example of displaying image in swing

  1. import java.awt.*;  
  2. import javax.swing.JFrame;  
  3.   
  4. public class MyCanvas extends Canvas{  
  5.       
  6.     public void paint(Graphics g) {  
  7.   
  8.         Toolkit t=Toolkit.getDefaultToolkit();  
  9.         Image i=t.getImage("p3.gif");  
  10.         g.drawImage(i, 120,100,this);  
  11.           
  12.     }  
  13.         public static void main(String[] args) {  
  14.         MyCanvas m=new MyCanvas();  
  15.         JFrame f=new JFrame();  
  16.         f.add(m);  
  17.         f.setSize(400,400);  
  18.         f.setVisible(true);  
  19.     }  
  20.   
  21. }