< Prev
Next >

Swing Framework

Swing framework gives us an ability to create window based applications and its easy to use graphical user interface(GUI). Swing Framework is part of Java Foundation Classes(JFC). Swing extends the capabilities of Abstract Window Toolkit(AWT) but, with a difference.

Difference between Swing and AWT?

Swing Framework consists of two main members -

Creating a simple Swing window application

To avoid the problem of deadlock in Swing based window applications, we must create the GUI of our window application using an Event Dispatching Thread and not the main thread.

In order to create and update the GUI of our window based application using Event Dispatching Thread, we must use one of the two methods defined by SwingUtilities class.
static void invokeLater(Runnable ob);
static void invokeAndWait(Runnable ob);
Where ob is a Runnable object, representing an Event Dispatching thread. Method run() of this Runnable object, ob, will be called by Event Dispatching Thread. The difference between the two methods is that invokeLater() method returns immediately whereas, invokeAndWait() method waits for the run method to complete its execution.

Swing example

import javax.swing.*;
//import java.awt.*;

public class SwingEx implements Runnable

public static void main(String...ar)
SwingUtilities.invokeLater(new SwingEx()); //Creating and calling an Event Dispatching Thread 

//Event Dispatching Thread is running to create GUI of window application
public void run() 
new A();


class A
JFrame frame;
JLabel label;

frame = new JFrame("Swing");
label = new JLabel("The is our first program of Swing");


When you run the code, you are presented a window showing the main container JFrame, which contains a component JLabel displaying a message like Figure1.

Figure 1.

Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter

< Prev
Next >
< ScrollBar
FlowLayout Manager >

Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page