Program to Display Image using Applet
Implementation of the AppletImage program is mentioned below:
Java
// Java Program to display image using Applet //Importing Necessary Packages import java.applet.Applet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; // Driver Class public class AppletImage extends Applet { private Image img; public void init() { // Loading the image from a local file (gfglogo.png) img = Toolkit.getDefaultToolkit().getImage( "gfglogo.png" ); } public void paint(Graphics g) { if (img != null ) { // Clearing the applet background initially g.setColor(Color.WHITE); g.fillRect( 0 , 0 , getWidth(), getHeight()); // Drawing a border around the image g.setColor(Color.BLACK); g.drawRect( 10 , 10 , getWidth() - 20 , getHeight() - 20 ); // Drawing the image, scaled to fit within the border int widImg = img.getWidth( this ); int heiImg = img.getHeight( this ); if (widImg > 0 && heiImg > 0 ) { int x = 20 ; int y = 20 ; int maxWid = getWidth() - 40 ; int maxHei = getHeight() - 40 ; // Calculating the new dimensions to fit within the border int nWid, nHei; if (widImg <= maxWid && heiImg <= maxHei) { nWid = widImg; nHei = heiImg; } else { double wRatio = ( double ) maxWid / widImg; double hRatio = ( double ) maxHei / heiImg; double scale = Math.min(wRatio, hRatio); nWid = ( int ) (widImg * scale); nHei = ( int ) (heiImg * scale); } g.drawImage(img, x, y, nWid, nHei, this ); } // Adding a title text g.setColor(Color.BLACK); g.setFont( new Font( "SansSerif" , Font.BOLD, 16 )); g.drawString( "w3wiki Logo" , 20 , getHeight() - 10 ); } } } |
Output for the program
Explanation of the Program
- We have imported the packages which are necessary to define the Applet and the Label to display the image name in the application.
- Then we have defined the AppletImage class which is implementing the ActionListener interface.
- There is an init() method, which is responsible for loading the gfglogo.png image from the local disk of the system.
- We have defined the paint() method, which performs the entire functionality of displaying the image to the Applet. We have set the custom color to the Applet window, also, we have defined the dimensions in which the gfglogo will be displayed on the Applet window.
- We have customized the appearance of the image by adding a border to it. Also, we have added the image title text using the drawString() method.
How to Display Image using Applet?
In this article, we will be using the Applet to display the image in proper layout. Here, we will display the image along with the text in the Applet Viewer.