gui programs in java

Last Updated on August 30, 2023

Right here on Collegelearners, you are privy to a litany of relevant information on java gui source code examples, java gui projects, java swing examples with source code, and so much more. Take out time to visit our catalog for more information on similar topics.

gui programs in java

Java Programming Tutorial

Programming Graphical User Interface (GUI)

1.  Introduction

So far, we have covered the basic programming constructs (such as variables, data types, decision, loop, array and method) and introduced the important concept of Object-Oriented Programming (OOP). As discussed, OOP permits higher level of abstraction than traditional Procedural-Oriented Languages (such as C). You can create high-level abstract data types called classes to mimic real-life things. These classes are self-contained and are reusable.

In this article, I shall show you how you can reuse the graphics classes provided in JDK for constructing your own Graphical User Interface (GUI) applications. Writing your own graphics classes (and re-inventing the wheels) is mission impossible! These graphics classes, developed by expert programmers, are highly complex and involve many advanced design patterns.  However, re-using them are not so difficult, if you follow the API documentation, samples and templates provided.

I shall assume that you have a good grasp of OOP, including composition, inheritance, polymorphism, abstract class and interface; otherwise, read the earlier articles. I will describe another important OO concept called nested class (or inner class) in this article.

There are current three sets of Java APIs for graphics programming: AWT (Abstract Windowing Toolkit), Swing and JavaFX.

  1. AWT API was introduced in JDK 1.0. Most of the AWT UI components have become obsolete and should be replaced by newer Swing UI components.
  2. Swing API, a much more comprehensive set of graphics libraries that enhances the AWT, was introduced as part of Java Foundation Classes (JFC) after the release of JDK 1.1. JFC consists of Swing, Java2D, Accessibility, Internationalization, and Pluggable Look-and-Feel Support APIs. JFC has been integrated into core Java since JDK 1.2.
  3. The latest JavaFX, which was integrated into JDK 8, was meant to replace Swing. JavaFX was moved out from the JDK in JDK 11, but still available as a separate module.

Other than AWT/Swing/JavaFX graphics APIs provided in JDK, other organizations/vendors have also provided graphics APIs that work with Java, such as Eclipse’s Standard Widget Toolkit (SWT) (used in Eclipse), Google Web Toolkit (GWT) (used in Android), 3D Graphics API such as Java bindings for OpenGL (JOGL), Java3D, and etc. Furthermore, developers have moved to use technologies such as HTML5 as the basis of webapps.

You need to refer to the “JDK API documentation” for the AWT/Swing APIs (under module java.desktop) while reading this chapter. The best online reference for Graphics programming is the “Swing Tutorial”

2.  Programming GUI with AWT

I shall start with the AWT before moving into Swing to give you a complete picture of Java Graphics.

2.1  AWT Packages

AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with 18 packages of 737 classes as of JDK 8). Fortunately, only 2 packages – java.awt and java.awt.event – are commonly-used.

  1. The java.awt package contains the core AWT graphics classes:
    • GUI Component classes, such as ButtonTextField, and Label.
    • GUI Container classes, such as Frame and Panel.
    • Layout managers, such as FlowLayoutBorderLayout and GridLayout.
    • Custom graphics classes, such as GraphicsColor and Font.
  2. The java.awt.event package supports event handling:
    • Event classes, such as ActionEventMouseEventKeyEvent and WindowEvent,
    • Event Listener Interfaces, such as ActionListenerMouseListener, MouseMotionListenerKeyListener and WindowListener,
    • Event Listener Adapter classes, such as MouseAdapterKeyAdapter, and WindowAdapter.

AWT provides a platform-independent and device-independent interface to develop graphic programs that runs on all platforms, including Windows, macOS, and Unixes.

2.2  AWT Containers and Components


There are two groups of GUI elements:

  1. Component (WidgetControl): Components are elementary GUI entities, such as ButtonLabel, and TextField. They are also called widgetscontrols in other graphics systems.
  2. Container: Containers, such as Frame and Panel, are used to hold components in a specific layout (such as FlowLayout or GridLayout). A container can also hold sub-containers.

In the above figure, there are three containers: a Frame and two Panels. A Frame is the top-level container of an AWT program. A Frame has a title bar (containing an icon, a title, and the minimize/maximize/close buttons), an optional menu bar and the content display area. A Panel is a rectangular area used to group related GUI components in a certain layout. In the above figure, the top-level Frame contains two Panels. There are five components: a Label (providing description), a TextField (for users to enter text), and three Buttons (for user to trigger certain programmed actions).

In a GUI program, a component must be kept (or added) in a container. You need to identify a container to hold the components. Every container has a method called add(Component c). A container (say aContainer) can invoke aContainer.add(aComponent) to add aComponent into itself. For example,

Panel pnl = new Panel();          // Panel is a container
Button btn = new Button("Press"); // Button is a component
pnl.add(btn);                     // The Panel container adds a Button component

GUI components are also called controls (e.g., Microsoft ActiveX Control), widgets (e.g., Eclipse’s Standard Widget Toolkit, Google Web Toolkit), which allow users to interact with (or control) the application.

2.3  AWT Container Classes

Top-Level Containers: Frame, Dialog and Applet

Each GUI program has a top-level container. The commonly-used top-level containers in AWT are FrameDialog and Applet:

  • AWT_Frame.pngFrame provides the “main window” for your GUI application. It has a title bar (containing an icon, a title, the minimize, maximize/restore-down and close buttons), an optional menu bar, and the content display area. To write a GUI program, we typically start with a subclass extending from java.awt.Frame to inherit the main window as follows:import java.awt.Frame; // Using Frame class in package java.awt // A GUI program is written as a subclass of Frame – the top-level container // This subclass inherits all properties from Frame, e.g., title, icon, buttons, content-pane public class MyGUIProgram extends Frame { // private variables …… // Constructor to setup the GUI components and event handlers public MyGUIProgram() { …… } // The entry main() method public static void main(String[] args) { // Invoke the constructor (to setup the GUI) by allocating an instance new MyGUIProgram(); } }
  • AWT_Dialog.gifAn AWT Dialog is a “pop-up window” used for interacting with the users. A Dialog has a title-bar (containing an icon, a title and a close button) and a content display area, as illustrated.
  • An AWT Applet (in package java.applet) is the top-level container for an applet, which is a Java program running inside a browser. Applet is no longer supported in most of the browsers.
Secondary Containers: Panel and ScrollPane

Secondary containers are placed inside a top-level container or another secondary container. AWT provides these secondary containers:

  • Panel: a rectangular box used to layout a set of related GUI components in pattern such as grid or flow.
  • ScrollPane: provides automatic horizontal and/or vertical scrolling for a single child component.
  • others.
Hierarchy of the AWT Container Classes

The hierarchy of the AWT Container classes is as follows:AWT_ContainerClassDiagram1.png

As illustrated, a Container has a LayoutManager to layout the components in a certain pattern, e.g., flow, grid.

2.4  AWT Component Classes

AWT provides many ready-made and reusable GUI components in package java.awt. The frequently-used are: ButtonTextFieldLabelCheckboxCheckboxGroup (radio buttons), List, and Choice, as illustrated below.AWT_Components.png

AWT GUI Component: java.awt.Label


java.awt.Label provides a descriptive text string. Take note that System.out.println() prints to the system console, NOT to the graphics screen. You could use a Label to label another component (such as text field) to provide a text description.

Check the JDK API specification for java.awt.Label.


public Label(String strLabel, int alignment); // Construct a Label with the given text String, of the text alignment
public Label(String strLabel);                // Construct a Label with the given text String
public Label();                               // Construct an initially empty Label

The Label class has three constructors:

  1. The first constructor constructs a Label object with the given text string in the given alignment. Note that three static constants Label.LEFTLabel.RIGHT, and Label.CENTER are defined in the class for you to specify the alignment (rather than asking you to memorize arbitrary integer values).
  2. The second constructor constructs a Label object with the given text string in default of left-aligned.
  3. The third constructor constructs a Label object with an initially empty string. You could set the label text via the setText() method later.

Constants (final static fields)

public static final LEFT;    // Label.LEFT
public static final RIGHT;   // Label.RIGHT
public static final CENTER;  // Label.CENTER

These three constants are defined for specifying the alignment of the Label‘s text, as used in the above constructor.

Public Methods

// Examples
public String getText();
public void setText(String strLabel);
public int getAlignment();
public void setAlignment(int alignment);  // Label.LEFT, Label.RIGHT, Label.CENTER

The getText() and setText() methods can be used to read and modify the Label‘s text. Similarly, the getAlignment() and setAlignment() methods can be used to retrieve and modify the alignment of the text.

Constructing a Component and Adding the Component into a Container

Three steps are necessary to create and place a GUI component:

  1. Declare the component with an identifier (name);
  2. Construct the component by invoking an appropriate constructor via the new operator;
  3. Identify the container (such as Frame or Panel) designed to hold this component. The container can then add this component onto itself via aContainer.add(aComponent) method. Every container has a add(Component) method. Take note that it is the container that actively and explicitly adds a component onto itself, NOT the other way.


Label lblInput;                     // Declare an Label instance called lblInput
lblInput = new Label("Enter ID");   // Construct by invoking a constructor via the new operator
add(lblInput);                      // this.add(lblInput) - "this" is typically a subclass of Frame
lblInput.setText("Enter password"); // Modify the Label's text string
lblInput.getText();                 // Retrieve the Label's text string
An Anonymous Label Instance

You can create a Label without specifying an identifier, called anonymous instance. In the case, the Java compiler will assign an anonymous identifier for the allocated object. You will not be able to reference an anonymous instance in your program after it is created. This is usually alright for a Label instance as there is often no need to reference a Label after it is constructed.


// Allocate an anonymous Label instance.
// "this" container adds the instance.
// You CANNOT reference an anonymous instance to carry out further operations.
add(new Label("Enter Name: ", Label.RIGHT));
// Same as
Label xxx = new Label("Enter Name: ", Label.RIGHT)); // xxx assigned by compiler
AWT GUI Component: java.awt.Button


java.awt.Button is a GUI component that triggers a certain programmed action upon clicking.


public Button(String btnLabel);
   // Construct a Button with the given label
public Button();
   // Construct a Button with empty label

The Button class has two constructors. The first constructor creates a Button object with the given label painted over the button. The second constructor creates a Button object with no label.

Public Methods

public String getLabel();
   // Get the label of this Button instance
public void setLabel(String btnLabel);
   // Set the label of this Button instance
public void setEnable(boolean enable);   
   // Enable or disable this Button. Disabled Button cannot be clicked.

java gui source code examples

Java GUI Source Code Examples Know How To Create GUI With Examples

ByLukeJune 19, 20210

java gui

Swing in java & java gui becomes part of Java foundation class which is lightweight and platform independent. It is utilized for creating window based applications. It includes elements such as button, scroll bar and text field and so on.

Java GUI Source Code Examples Know How To Create GUI With Examples

In this article, you can know about java gui here are the details below;

Putting together all these elements makes a graphical user interface. In this content, we will go into the ideas associated with the procedure of building applications utilizing swing in Java. Following are the concepts talked about in this article:

What is Swing In Java?

Swing in Java is a light-weight GUI toolkit which has a wide range of widgets for constructing enhanced window based app. It is a member of the JFC( Java Structure Classes). It is build on best of the AWT API and completely written in java. It is platform autonomous unlike AWT and has light-weight components.
It ends up being much easier to construct applications given that we currently have GUI components like button, checkbox and so on. This is valuable since we do not need to begin with the scratch. Also check another post like discord javascript error.

Container Class

Any class which has other parts in it is called as a container class. For constructing GUI applications a minimum of one container class is necessary.
Following are the 3 kinds of container classes:

1. Panel– It is utilized to organize parts on to a window
2. Frame– A totally functioning window with icons and titles
3. Dialog– It resembles a turn up window however not fully practical like the frame

Difference In Between AWT and Swing

– Platform Dependent – Platform Independent
– Does not follow MVC – Follows MVC
– Lesser Components – More effective parts
– Does not support pluggable look – Supports pluggable feel and look
– Heavyweight – Lightweight.

Java Swing Class Hierarchy.

java gui

Explanation: All the elements in swing like JButton, JComboBox, JList, JLabel are inherited from the JComponent class which can be contributed to the container classes. Boxes are the windows like frame & dialog boxes. Fundamental swing components are the foundation of any gui application. Methods like setLayout bypass the default design in each container. Containers such as JFrame and JDialog can just add a component to itself. Following are a couple of parts with examples to comprehend how we can use them. Also check scala vs java.

JButton Class.

It is used to build a labelled button. Utilizing the ActionListener it will lead to some action when the switch is pushed. It inherits the AbstractButton class & is platform independent.


123456789101112import javax.swing.*;public class example{public static void main(String args[]) {JFrame a = new JFrame("example");JButton b = new JButton("click me");b.setBounds(40,90,85,20);a.add(b);a.setSize(300,300);a.setLayout(null);a.setVisible(true);}}


java gui

JTextField Class.

It inherits the JTextComponent room & it is utilized to enable editing of single line text.

123456789101112import javax.swing.*;public class example{public static void main(String args[]) {JFrame a = new JFrame("example");JTextField b = new JTextField("techolac");b.setBounds(50,100,200,30);a.add(b);a.setSize(300,300);a.setLayout(null);a.setVisible(true);}}


JScrollBar Class.

It is used to include scroll bar, both horizontal and vertical.


123456789101112131415import javax.swing.*;class example{example(){JFrame a = new JFrame("example");JScrollBar b = new JScrollBar();b.setBounds(90,90,40,90);a.add(b);a.setSize(300,300);a.setLayout(null);a.setVisible(true);}public static void main(String args[]){new example();}}


java gui

JPanel Class.

It acquires the JComponent class and supplies space for an application which can connect any other part.

1234567891011121314151617181920import java.awt.*;import javax.swing.*;public class Example{Example(){JFrame a = new JFrame("example");JPanel p = new JPanel();p.setBounds(40,70,200,200);JButton b = new JButton("click me");b.setBounds(60,50,80,40);p.add(b);a.add(p);a.setSize(400,400);a.setLayout(null);a.setVisible(true);}public static void main(String args[]){new Example();}}


java gui

JMenu Class.

About the author

Study on Scholarship Today -- Check your eligibility for up to 100% scholarship.