Udemy logo

149185466A Graphical User Interface (GUI) is one of the most important parts of an application since it is the primary medium for end users to communicate with a system. A good GUI increases the productivity and efficiency of a system. In contrast, text command systems reduce efficiency for a user, because it requires users to type a text command for executing required functionality every time. Different programming languages provide libraries for GUI creation with less effort. In Java, the swing package is introduced as a GUI toolkit.

For more Java Swing tutorials, look at this Udemy.com course.

What is the Swing GUI?

Swing, a GUI toolkit, is part of the Java Foundation Classes (JFC). Complete packages of the ‘Swing GUI’ is located in ‘javax.swing’. The package is all written in Java and provides an API for creating a graphical user interface for all Java programs.  The following are the main properties of a ‘Swing GUI’ toolkit.

How to Use the Swing GUI toolkit

The ‘JComponent’ class is the root class for almost all of the GUI components in ‘Swing GUI’ toolkit. Therefore, each program that uses the ‘Swing GUI’ toolkit has at least one top-level container and each top-level container has a content pane that contains the visible interface components of a ‘Swing GUI’. The Menu bar is also a part of the top-level container and positioned at the top by default, but outside of the content pane. The following example demonstrate the use of ‘JFrame’, one of the top-level containers to show a label containing a ‘Hello World’ string.

Code snippet:

import javax.swing.*;
public class SwingExample extends JFrame {
public SwingExample () {
setTitle ("First Swing Example");
setSize (300, 200);
setLocationRelativeTo (null);
JLabel lblHelloWorld = new JLabel ("Hello World");
add (lblHelloWorld);
setDefaultCloseOperation (EXIT_ON_CLOSE);
public static void main (String[] args) {
             invokeLater (new Runnable () {
publicvoid run () {
SwingExample ex = new SwingExample ();
ex.setVisible (true);
} );

In the above code snippet, the ‘Swing GUI’ package is imported in the ‘SwingExample’ class. This class then inherits from the class ‘JFrame’, a top-level container that provides a content pane to a class. The ‘setTitle’ method sets the title of an output window and ‘setSize’ specifies its size (width and height). The ‘setLocationRelativeTo’ shows the window at the center of a screen. A ‘Swing GUI’ label is then initialized with a text and adds it to a container by calling ‘add’ method. The ‘setDefaultCloseOperation’ method with an argument of ‘EXIT_ON_CLOSE’, a static final integer with a value of ‘3’ is used to close the window by clicking the close icon on title bar. Finally, the ‘invokeLater’ method places the application on the Swing Event Queue and executes a ‘run’ method asynchronously which ensures that all UI updates are not concurrent since ‘Swing’ is not thread safe.

For more interesting Java tutorials, take this Udemy.com course.

Swing GUI Toolkit Basic Components

Some of the basic interface components of ‘Swing GUI’ are ‘JPanel’, ‘JTextField’, ‘JCheckBox’ and ‘JButton’. Following is the description.

Code snippet:

final JPanel panel = new JPanel ();
getContentPane ().add (panel);
panel.setLayout (null);
panel.setToolTipText ("A JPanel holds a JButton");
final JTextField textField = new JTextField (50);
textField.setBounds (75, 50, 150, 25);
panel.add (textField);
final JCheckBox checkbox = new JCheckBox ("Hide TextField", true);
checkbox.setBounds (10, 150, 150, 80);
checkbox.setFocusable (false);
checkbox.setSelected (false);
checkbox.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent event) {
boolean state = checkbox.isSelected ();
if (state) {
textField.setVisible (false);
} else {
textField.setVisible (true);
panel.add (checkbox);
JButton btnAddLabel = new JButton ("Enter Text and Click it");
btnAddLabel.setBounds (50, 100, 200, 30);
btnAddLabel.setToolTipText ("A JButton sets a label with JTextField text");
btnAddLabel.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent event) {
JLabel lblHelloWorld = new JLabel ();
lblHelloWorld.setBounds (10, 0, 100, 30);
panel.add (lblHelloWorld);
panel.updateUI ();
panel.add (btnAddLabel);
setTitle ("Swing Button Example");
setSize (300, 300);
setLocationRelativeTo (null);
setDefaultCloseOperation (EXIT_ON_CLOSE);

In the above code snippet, A ‘JPanel’ is added to a ‘JFrame’ content pane to manage other ‘Swing GUI’ components. An ‘updateUI’ method of a ‘JPanel’ refreshes the components state. Thus, the changes made to a component appear in a GUI.

Swing GUI Menu

A Swing GUI ‘JMenu’ is a single pull-down list with commands, located in a ‘JMenuBar’. A ‘JMenu’ has ‘JMenuItem’ with some common command used in the application. A ‘JMenuBar’ has several ‘JMenu’ objects and each ‘JMenu’ has a number of ‘JMenuItem’ objects which in turn have some sub-menu items as ‘JMenuItem’. Following code snippet demonstrate above concepts in action via basic example having ‘JMenuBar’, ’JMenu’ and ‘JMenuItem’ implementation.

 Code snippet:

JMenuBar menubar = new JMenuBar ();
JMenu fileMenuItem = new JMenu ("File");
fileMenuItem.setMnemonic (KeyEvent.VK_F);
JMenu newProItem = new JMenu ("New");
newProItem.setMnemonic (KeyEvent.VK_N);
JMenuItem newOpenFileItem = new JMenuItem ("Open File...");
newOpenFileItem.setMnemonic (KeyEvent.VK_O);
newOpenFileItem.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_OCTRL_MASK));
JMenuItem newJava = new JMenuItem ("Java Project");
JMenuItem bookAndroid = new JMenuItem ("Android Application Project");
JMenuItem project = new JMenuItem ("Project...");
newProItem.add (newJava);
newProItem.add (bookAndroid);
newProItem.add (project);
JMenuItem exitItem = new JMenuItem ("Exit");
exitItem.setMnemonic (KeyEvent.VK_E);
exitItem.setToolTipText ("Exit application");
exitItem.setAccelerator (KeyStroke.getKeyStroke (KeyEvent.VK_ECTRL_MASK));
exitItem.addActionListener (new ActionListener () {
publicvoid actionPerformed (ActionEvent event) { exit (0)}
fileMenuItem.add (newProItem);
fileMenuItem.add (newOpenFileItem);
fileMenuItem.add (exitItem);
menubar.add (fileMenuItem);
setJMenuBar (menubar);
setTitle ("Swing Menu Example");
setSize (300, 200);
setLocationRelativeTo (null);
setDefaultCloseOperation (EXIT_ON_CLOSE);

In the above example, a method ‘setMnemonic’ is used to assign a shortcut to the command associated with a ‘JMenuItem’ but it only works when a menu bar is in selected mode. However, a method ‘setAccelerator’ assigns a shortcut that is used from a whole application any time.

Java Swing GUI components are light weight and adopt the look and feel of the underlying operating system. This saves programmers time, so they can explicitly program the look and feel of GUI based Java applications for individual platforms. Putting everything together, Swing GUI has now become standard for developing GUI for Java based applications and should be adopted whenever GUI components are required to be integrated in a Java application.

To learn more about Java Swing, check out this course at Udemy.com.

Page Last Updated: June 2014

Top courses in Java

Java for Beginners
Navin Reddy
4.6 (1,229)
Mastering Java Reactive Programming [ From Scratch ]
Vinoth Selvaraj
4.6 (2,020)
Java Interview Help
Bharath Thippireddy
4.5 (1,458)
Java SE 11 Developer 1Z0-819 OCP Course - Part 1
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.6 (3,964)
Java 8 New Features In Simple Way
4.6 (15,005)
Learn Selenium with Java, Cucumber & Frameworks
Pavan Kumar
4.6 (6,859)
Modern Java - Learn Java 8 Features By coding it
Pragmatic Code School
4.5 (10,699)
Java 21, Java 17, Java 11 and Advanced Java 8
Dr. Seán Kennedy OCA, OCP
4.4 (1,142)

More Java Courses

Java students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo