Swing

Swing Framework contains a set of classes that provides more powerful and flexible GUI components than those of AWT. Swing provides the look and feel of modern Java GUI. Swing library is an official Java GUI tool kit released by Sun Microsystems. It is used to create graphical user interface with Java.


Main Features of Swing Toolkit

  1. Platform Independent
  2. Customizable
  3. Extensible
  4. Configurable
  5. Lightweight

Swing and JFC

JFC is an abbreviation for Java Foundation classes, which encompass a group of features for building Graphical User Interfaces(GUI) and adding rich graphical functionalities and interactivity to Java applications.


Features of JFC

  • Swing GUI components.
  • Look and Feel support.
  • Java 2D.

Introduction to Swing Classes

JPanel : JPanel is Swing's version of AWT class Panel and uses the same default layout, FlowLayout. JPanel is descended directly from JComponent.

JFrame : JFrame is Swing's version of Frame and is descended directly from Frame class. The component which is added to the Frame, is refered as its Content.

JWindow : This is Swing's version of Window and hass descended directly from Window class. Like Window it uses BorderLayout by default.

JLabel : JLabel descended from Jcomponent, and is used to create text labels.

JButton : JButton class provides the functioning of push button. JButton allows an icon, string or both associated with a button.

JTextField : JTextFields allow editing of a single line of text.


Creating a JFrame

There are two way to create a JFrame Window.

  1. By instantiating JFrame class.
  2. By extending JFrame class.

Creating JFrame window by Instantiating JFrame class

import javax.swing.*;
import java.awt.*;
public class First 
{
 JFrame jf;
 public First() {
 jf = new JFrame("MyWindow");		//Creating a JFrame with name MyWindow.
 JButton btn = new JButton("Say Hello");	//Creating a Button. 
 jf.add(btn);             		//adding button to frame.
 jf.setLayout(new FlowLayout());        //setting layout using FlowLayout object.
 jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	//setting close  operation.
 jf.setSize(400, 400);            	//setting size
 jf.setVisible(true);            	//setting frame visibilty
}
 public static void main(String[] args) 
 {
  new First();
 }
}


Creating JFrame window by extending JFrame class

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Second extends JFrame
{
 public Second() 
 {
  setTitle("MyWindow");
  JLabel lb = new JLabel("Welcome to My Second Window");	//Creating a label.
  add(lb);			//adding label to frame. 
  setLayout(new FlowLayout());	//setting layout using FlowLayout object. 
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		//setting close operation. 
  setSize(400, 400);		//setting size 
  setVisible(true);		//setting frame visibilty 
 }
 public static void main(String[] args) 
 {
  new Second();
 }
}