Wednesday 7 October 2020

How To Add Image in Java Swing JFrame using JLabel

                      In this post, we will see How To Add Image in Java Swing JFrame using JLabel.

                    To know what is Swing, how Swing is different from Applet, how to create Swing Application; check this post http://www.comrevo.com/2017/08/swing-in-java-with-example.html                    

                    To know how to generate event in Java Swing along with Java Swing program for addition of two numbers; check this post http://www.comrevo.com/2017/08/java-swing-program-for-addition-of-two-numbers.html 

  
                    Here, we will see Java Swing program for adding Image on frame.  

                    In Swing, there are different ways to add image on frame e.g. using paint() method or using JPanel class. 
                    But, the best way to add image is by using JLabel class. We need to create JLabel object. While creating JLabel object, we need to pass object of ImageIcon class. While creating object of ImageIcon, we need to pass object of BufferedImage class. To create object of BufferedImage, we need to call read() method of ImageIO class. We have to pass object of File class into read() method as parameter. File object refers our image file

                    Go through the following program:

                                

Program (SwingImage.java):
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class SwingImage
{
   public static void main(String args[]) throws Exception
     {
       Abc obj=new Abc();
     }
}

class Abc extends JFrame 
{
  public Abc() throws Exception
   {

     setLayout(new FlowLayout());

     JLabel l1=new JLabel("Full Name:");
     JTextField t1=new JTextField(); 
     t1.setColumns(20);

     JLabel l2=new JLabel("Class:");
     JTextField t2=new JTextField();
     t2.setColumns(20);

     JLabel l3=new JLabel("College:");
     JTextField t3=new JTextField();
     t3.setColumns(20);

     JLabel l4=new JLabel("City");
     JTextField t4=new JTextField();
     t4.setColumns(20);

     JButton b1=new JButton("Submit");
     JButton b2=new JButton("Reset");

     add(l1);
     add(t1);
     add(l2);
     add(t2);
     add(l3);
     add(t3);
     add(l4);
     add(t4);
     add(b1);
     add(b2);
     
     BufferedImage myPicture = ImageIO.read(new File("thread life cycle.jpeg"));
     JLabel picLabel = new JLabel(new ImageIcon(myPicture));
     add(picLabel);
      
     setVisible(true);
     setSize(250,400);

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

How To Run:
parag@parag-Inspiron-N4010:~/Desktop/prog/swing$ javac SwingImage.java 
parag@parag-Inspiron-N4010:~/Desktop/prog/swing$ java SwingImage


  

Output: 


                        Check other posts on Java Programming in this link http://www.comrevo.com/2017/08/java-programming.html

No comments:

Post a Comment