Swing - SPLessons

Swing Application

Chapter 3

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Swing Application

Swing Application

shape Description

Before proceeding with the Swing further concepts user should have the basic knowledge of the AWT concepts and JAVA programming skills to create the window application. All AWT components will be repeated in Swing also with an extra functionalities because of the Swing components are lightweight components whereas AWT components are heavy weight components. The example to create an Swing Application is as follows.

SimpleWindow

shape Example

Below is the basic program to display the window of an Swing Application. Below is the source code of a Simple Window.

SimpleWindow.java

package swing;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class SimpleWindow extends JFrame {
	//SimpleWindow will inherit the properties from the JFrame component
    public SimpleWindow() {
        initUI();//create a method
    }
    private void initUI() {   
        setTitle("Simple example");//set the title
        setSize(300, 200);//set the size
        setLocationRelativeTo(null);//set the window to center
        setDefaultCloseOperation(EXIT_ON_CLOSE);//to close the window
    }
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() 
        //The invokeLater() method places the application on the Swing Event Queue. It is used to ensure that all UI updates are concurrency-safe.
        {
            @Override
            public void run() {
            	SimpleWindow sw = new SimpleWindow();//created the instance
                sw.setVisible(true);//to visible the window
            }
        });
    }
}

In the above code developer needs to import all the required packages as follows that is similar to all the Swing applications and all the Swing classes will be available in the imported packages.

import java.awt.EventQueue;
import javax.swing.JFrame;

Create a class SimpleWindow that should extend from the JFrame, because SimpleWindow inherits the properties from the JFrame. Create the constructor that should have the method as follows.

public SimpleWindow() {
 
        initUI();//create a method
    }

Set the title and size of the window.

setTitle("Simple example");
        setSize(300, 200);

Write the function to set the location of the window on the screen and to terminate the application.

setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

Create the object(sw) to make the window visible using setVisible(true); .

SimpleWindow sw = new SimpleWindow();//created the instance
                sw.setVisible(true);

To know the status of all the graphical user interface components, window application should be in EventQueue of the swing as follows.

EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        SimpleExample ex = new SimpleExample();
        ex.setVisible(true);
    }
});

Output:
After executing the above code successfully, the output will be as follows and it can be maximized or minimize.

QuitButton

shape Example

Below is an application which shows how to quit an Swing Application.

QuitButtonEx.java

package swing;

import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class QuitButtonEx extends JFrame {
//QuitButtonEx should inherit the properties of the JFrame.
    public QuitButtonEx() {

        initUI();
    }
    private void initUI() {
        JButton quitButton = new JButton("Quit");//created a button component
        quitButton.addActionListener(new ActionListener() {//plug an action listener to the button.
            @Override
            public void actionPerformed(ActionEvent event) {//listener's actionPerformed() method will be called when we click on the button.
                System.exit(0);//to terminate the application.
            }
        });

        createLayout(quitButton);

        setTitle("Quit button");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        
    }

    private void createLayout(JComponent... arg) {//default layout manager of a content pane is the BorderLayout manager.

        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);//developer use the GroupLayout manager which is more powerful and flexible.
        pane.setLayout(gl);

        gl.setAutoCreateContainerGaps(true);//setAutoCreateContainerGaps() method creates gaps between components and the edges of the container.

        gl.setHorizontalGroup(gl.createSequentialGroup()
        		.addComponent(arg[0])
        );

        gl.setVerticalGroup(gl.createSequentialGroup()
                .addComponent(arg[0])
        );
    }
    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {//default method
        
        	@Override
            public void run() {
                QuitButtonEx ex = new QuitButtonEx();
                ex.setVisible(true);//window will be visible here 
            }
        });
    }

Where developer created a QUIT component that creates constructor to take string label as a parameter.

 JButton quitButton = new JButton("Quit");

Set the gap between the components.

gl.setAutoCreateContainerGaps(true);

Listeners should be added to the button and when click on the button actionPerformed() method will be called as follows.

quitButton.addActionListener(new ActionListener() {//plug an action listener to the button.
            @Override
            public void actionPerformed(ActionEvent event) {//listener's actionPerformed() method will be called when we click on the button.
                System.exit(0);

To place an application on event queue invokelater() method will be use full.

EventQueue.invokeLater(new Runnable()

Output:
After executing the above code successfully. When the Quit button clicks in the below window, the application will be closed.

Summary

shape Key Points

  • Swing Application – Listeners ActionPerformed() will be done when clicked on the event like on Button.
  • setDefaultCloseOperation(EXIT_ON_CLOSE); is used to terminate the program.