«Back to Home

Core Java

Topics

Display Image In Swing Java

Display Image
 
In Swing Java, we can use the method drawImage() of Graphics class to display image.
 
Method drawImage()

public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)

This method is used to draw the specific image.
 
Let’s see an example of display image in Swing, given below.
 
Code
  1. import java.awt.*;  
  2. import javax.swing.JFrame;  
  3. public class DisplayImageExample extends Canvas {  
  4.     public void paint(Graphics g) {  
  5.         Toolkit t = Toolkit.getDefaultToolkit();  
  6.         Image i = t.getImage("B:\\photos\\2014-11-02\\C.jpg");  
  7.         g.drawImage(i, 150120this);  
  8.     }  
  9.     public static void main(String[] args) {  
  10.         DisplayImageExample die = new DisplayImageExample();  
  11.         JFrame jf = new JFrame();  
  12.         jf.add(die);  
  13.         jf.setSize(400400);  
  14.         jf.setVisible(true);  
  15.     }  
  16. }  
55

Output

56
 
Summary

Thus, we learnt that we can use the method drawImage() of Graphics class to display an image and also learnt how to display an image in Swing Java.