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                    

                    To know how to generate event in Java Swing along with Java Swing program for addition of two numbers; check this post 

                    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 (
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
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(); 

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

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

     JLabel l4=new JLabel("City");
     JTextField t4=new JTextField();

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

     BufferedImage myPicture = File("thread life cycle.jpeg"));
     JLabel picLabel = new JLabel(new ImageIcon(myPicture));


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



                        Check other posts on Java Programming in this link

No comments:

Post a Comment