Wednesday, 6 November 2013

JFrame in Swing Example for Beginners - Kickstart

The following example illustrates JFrame class in swing. This example covers the core methods of the javax.swing.JFrame and those of its super classes.

import javax.swing.*;
import java.awt.*;
import java.util.*;
class JFrameExample
{
    public static void main(String args[])
    {
    // Declare variables
    JFrame f1,f2;
   
    // Create a frame with 0,0 size and no title
    f1=new JFrame();
   
    // Set default look and feel decorated
    // This must be called before any frames
    // are created otherwise, there will be no effect
    // f1 doesn't have effect because it is already created above
    JFrame.setDefaultLookAndFeelDecorated(true);
   
    // Create a frame with title
    f2=new JFrame("Frame 2");
   
    // Set title for f1
    f1.setTitle("Frame 1");
   
    // Set size
    f1.setSize(400,400);
    f2.setSize(200,200);
   
    // Set some location for f1
    f1.setLocation(250,250);
   
    // Set location of f2 relative to desktop
    // appears at center of frame
    f2.setLocationRelativeTo(null);
   
    // Make f2 utility window
    f1.setType(Window.Type.UTILITY);
   
    // When close button is clicked exit program
    f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   
    // Show them
    f1.setVisible(true);
    f2.setVisible(true);
   
    // Bring f1 to front
    // because f1 goes back of f2
    f1.toFront();
   
    // or else you can send f2 back
    // f2.toBack();
   
    // Set icon images, most appropriate image (according to
    // dimension) is set among these
    // If this list contains several images of same size
    // first will be used
    ArrayList<Image> imgs=new ArrayList<>();
   
    // Get the toolkit
    Toolkit t=Toolkit.getDefaultToolkit();
   
    // Add images
    imgs.add(t.getImage("E:\\Wallpapers\\abstract triangle.jpg"));
    imgs.add(t.getImage("E:\\Wallpapers\\bluegradient1.jpg"));
    imgs.add(t.getImage("E:\\Wallpapers\\bmw.jpg"));
    imgs.add(t.getImage("E:\\Wallpapers\\ofthebluecolourofthesky.jpg"));
    imgs.add(t.getImage("E:\\Wallpapers\\Eiffiel Tower.jpg"));
   
    // Set the image of best dimensions
    f2.setIconImages(imgs);
   
    }
}

Also see 3 Ways to set icon image for JFrame and setting background color for JFrame.
JFrame in Swing Example

No comments:

Post a Comment