The Wayback Machine - https://web.archive.org/web/20240910101700/https://www.geeksforgeeks.org/java-awt-tutorial/
Open In App

Java AWT Tutorial

Last Updated : 11 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Java AWT or Abstract Window Toolkit is an API used for developing GUI(Graphic User Interfaces) or Window-Based Applications in Java. Java AWT is part of the Java Foundation Classes (JFC) that provides a way to build platform-independent graphical applications.

In this AWT tutorial, you will learn the basics of the AWT, including how to create windows, buttons, labels, and text fields. We will also learn how to add event listeners to components so that they can respond to user input.

By the end of this tutorial, you will have a good understanding of the AWT and be able to create simple GUIs in Java.

Java AWT Basics

Java AWT (Abstract Window Toolkit) is an API used to create Graphical User Interface (GUI) or Windows-based Java programs and Java AWT components are platform-dependent, which means they are shown in accordance with the operating system’s view. AWT is heavyweight, which means that its components consume resources from the underlying operating system (OS). The java.awt package contains AWT API classes such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List, and so on.

Points about Java AWT components

i. Components of AWT are heavy and platform dependent
ii. AWT has less control as the result can differ because of components are platform dependent.

Why AWT is Platform Independent?

The Java AWT utilizes the native platform subroutine to create API components such as TextField, CheckBox, and buttons. This results in a different visual format for these components on different platforms such as Windows, MAC OS, and Unix. The reason for this is that each platform has a distinct view of its native components. AWT directly calls this native subroutine to create the components, resulting in an AWT application resembling a Windows application on Windows OS, and a Mac application on the MAC OS. In simpler terms, the AWT application’s appearance adapts to the platform it is running on.

AWT is platform independent even after the AWT components are platform dependent because of the points mentioned below:

1. JVM (Java Virtual Machine):

As Java Virtual Machine is platform dependent

2. Abstract APIs:

AWT provides an abstract layer for GUI. Java applications interact with AWT through Abstract API which are platform independent. Abstract API allows Java to isolate platform-specific details, making code portable across different systems.

3. Platform-Independent Libraries:

The Libraries of AWT are written in Java which they are totally platform-independent. Because of this, it ensures that AWT functionality remains consistent across different environments.

Java AWT Hierarchy

Java-AWT-Tutorial-Large

  • Components: AWT provides various components such as buttons, labels, text fields, checkboxes, etc used for creating GUI elements for Java Applications.
  • Containers: AWT provides containers like panels, frames, and dialogues to organize and group components in the Application.
  • Layout Managers: Layout Managers are responsible for arranging data in the containers some of the layout managers are BorderLayout, FlowLayout, etc.
  • Event Handling: AWT allows the user to handle the events like mouse clicks, key presses, etc. using event listeners and adapters.
  • Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert images and write text in the components of a Java Application.

Note: Container can be added inside another container as it is type of component.

Types of Containers in Java AWT

There are four types of containers in Java AWT:

  1. Window: Window is a top-level container that represents a graphical window or dialog box. The Window class extends the Container class, which means it can contain other components, such as buttons, labels, and text fields.
  2. Panel: Panel is a container class in Java. It is a lightweight container that can be used for grouping other components together within a window or a frame.
  3. Frame: The Frame is the container that contains the title bar and border and can have menu bars.
  4. Dialog: A dialog box is a temporary window an application creates to retrieve user input.

Java AWT Tutorial for Beginner & Experienced

Learn the basics of the Abstract Window Toolkit (AWT) in Java, for both beginners and experienced developers.

1. Java AWT Label

Syntax of AWT Label

public class Label extends Component implements Accessible  

AWT Label Class Constructors

There are three types of Java AWT Label Class

1. Label():
Creates Empty Label.

2. Label(String str):
Constructs a Label with str as its name.

3. Label(String str, int x):
Constructs a label with the specified string and x as the specified alignment

2. Java AWT Button

AWT Button is a control component with a label that generates an event when clicked on. Button Class is used for creating a labeled button that is platform-independent.

Syntax of AWT Button

public class Button extends Component implements Accessible  

Java AWT Button Class Constructors

There are two types of Button class constructors as mentioned below:

1. Button( ):
Creates a Button with no label i.e. showing an empty box as a button.

2. Button(String str): 
Creates a Button with String str as a label. For example if str=”Click Here” button with show click here as the value.

3. Java AWT TextField

Syntax of AWT TextField:

public class TextField extends TextComponent 

TextField Class constructors

There are TextField class constructors are mentioned below:

1. TextField():
Constructs a TextField component.

2. TextField(String text):
Constructs a new text field initialized with the given string str to be displayed.

3. TextField(int col):
Creates a new text field(empty) with the given number of columns (col).

4. TextField(String str, int columns):
Creates a new text field(with String str in the display) with the given number of columns (col).

4. Java AWT Checkbox

Syntax of AWT Checkbox:

public class Checkbox extends Component implements ItemSelectable, Accessible  

Checkbox Class Constructors

There are certain constructors in the AWT Checkbox class as mentioned below:

1. Checkbox():
Creates a checkbox with no label.

2. Checkbox(String str):
Creates a checkbox with a str label.

3. Checkbox(String str, boolean state, CheckboxGroup group):
Creates a checkbox with the str label, and sets the state in the mentioned group.

5. Java AWT CheckboxGroup

CheckboxGroup Class is used to group together a set of Checkbox.

Syntax of AWT CheckboxGroup:

public class CheckboxGroup extends Object implements Serializable  

Note: CheckboxGroup enables the use of radio buttons in AWT.

6. Java AWT Choice

The object of the Choice class is used to show a popup menu of choices.

Syntax of AWT Choice:

public class Choice extends Component implements ItemSelectable, Accessible 

AWT Choice Class constructor

Choice(): It creates a new choice menu.

7. Java AWT List

The object of the AWT List class represents a list of text items.

Syntax of Java AWT List:

public class List extends Component implements ItemSelectable, Accessible 

AWT List Class Constructors

The List of class constructors is defined below:

1. List():
Creates a new list.

2. List(int row):
Creates lists for a given number of rows(row).

3. List(int row, Boolean Mode)
Ceates new list initialized that displays the given number of rows.

8. Java AWT Canvas

Syntax of AWT Canvas:

public class Canvas extends Component implements Accessible  

Canvas Class Constructors

1. Canvas():
Creates new Canvas.

2. Canvas(GraphicConfiguration config):
It creates a new Canvas with the given Graphic configuration.

9. AWT Scrollbar

Syntax of AWT Scrollbar:

public class Scrollbar extends Component implements Adjustable, Accessible 

Java AWT Scrollbar Class Constructors

There are three constructor classes in Java mentioned below:

1. Scrollbar():
   It Creates a new vertical Scrollbar in the Application.

2. Scrollbar(int orientation):
   Creates a new vertical Scrollbar with the given orientation.

3. Scrollbar(int orientation, int value, int visible, int mini, int maxi):
    Creates a new scrollbar with the orientation mentioned with value as the default value and [mini, maxi] as the lower and higher limit.

MenuItem class adds a simple labeled menu item on the menu. The MenuItem class allows you to create individual items that can be added to menus. And Menu is a component used to create a dropdown menu that can contain a list of MenuItem components.

 Syntax of Java AWT MenuItem

public class MenuItem extends MenuComponent implements Accessible  

Syntax of Java AWT Menu

public class Menu extends MenuItem implements MenuContainer, Accessible  

Java AWT PopupMenu is a component that is used for dynamically popping up a menu that appears when the user right-clicks or performs any other action on a component.

Syntax of AWT PopupMenu

public class PopupMenu extends Menu implements MenuContainer, Accessible  

12. Java AWT Panel

Java AWT Panel is a container class used to hold and organize graphical components in a Java Application.

Syntax of Java AWT Panel:

public class Panel extends Container implements Accessible  

13. Java AWT Toolkit

Java AWT Toolkit class provides us with a platform-independent way to access various system resources and functionalities. Subclasses of Toolkit are used to bind various components.

Syntax of Java AWT Toolkit

public abstract class Toolkit extends Object  

Event Handling Components – Java AWT

Here are some of the event handling components in Java:

1. Java ActionListener

Java ActionListner is a interface which responds to the actions performed by the components like buttons, menu items ,etc.

Syntax of Java ActionListener:

public class ActionListenerExample Implements ActionListener  

There is only methods associated with ActionListner class that is actionPerformed().

Syntax of actionPerformed() method:

public abstract void actionPerformed(ActionEvent e);  

2. Java MouseListener

Java MouseListner is a interface that responds to the actions performed by mouse events generated by the user. Example: mouse clicks , mouse movements, etc.

There are 5 Methods associated with MouseListner:

1. mouseClicked(MouseEvent e):
Responds to mouse buttons when clicked on a component in the Application.

2. mousePressed(MouseEvent e):
Responds to mouse button is Pressed on a component in the Application.

3. mouseReleased(MouseEvent e):
Responds to Mouse button released after being pressed over a component in the Application.

4. mouseEntered(MouseEvent e):
Responds to the situation when a Mouse cursor enters the bounds of a component in an Application.

5. mouseExited(MouseEvent e):
Responds to the situation when a Mouse cursor exits a component’s bounds.

3. Java MouseMotionListener

Java MouseMotionListner is a interface which is notified when mouse is moved or dragged.

It contains two Methods mentioned below:

1. mouseDragged(MouseEvent e):
Responds when the mouse is dragged with mouse button clicked over a component in Application.

2. mouseMoved(MouseEvent e):
Responds when the mouse is moved over a component in Application.

4. Java ItemListener

Java ItemListner is an interface which handles events related to item selection and deselection those that occur with checkboxes, radio buttons, etc. There is only one Method associated with ItemListner that is itemStateChanged(). This method provides information about the event, i.e. source of the event and the changed state.

Syntax of itemStateChanged() method:

itemStateChanged(ItemEvent e)

5. Java KeyListener

Java KeyListner is an interface in Java notified whenever you change the state of key or can be said for key related events.

Syntax of KeyListener:

public interface KeyListener extends EventListener 

There are three methods associated with KeyListner as mentioned below:

1. keyPressed (KeyEvent e):
Responds to the event when key is pressed.

2. keyReleased (KeyEvent e):
Responds to the event when the key is released.

3. keyTyped (KeyEvent e):
Responds to the key has been typed.

6. Java WindowListener

Java WindowListener is a interface used for handling events related to window actions. Events like opening , closing, minimizing, etc are handled using WindowListener.

Syntax of WindowListener

public interface WindowListener extends EventListener 

There are seven methods associated with WindowListener as mentioned below:

1. windowActivated (WindowEvent e):
Responds when window is first opened

2. windowClosed (WindowEvent e):
Responds when the user attempts to close the window

3. windowClosing (WindowEvent e):
Responds after a window has been closed

4. windowDeactivated (WindowEvent e):
Responds when a window is minimized

5. windowDeiconified (WindowEvent e):
Responds when a window is restored from a minimized state

6. windowIconified (WindowEvent e):
Responds when a window is activated

7. windowOpened (WindowEvent e):
Responds when a window loses focus

7. Java Adapter classes

Java adapter classes provide the default implementation of listener interfaces.

8. Close AWT Window

At the end we will need to Close AWT Window, So to perform this task we will use dispose() method. This method releases the resources associated with the window and also removes it from the screen.

Java AWT Examples

Here are some Java AWT examples:

1. Hello World in Java AWT

Hello, World is was the first step in learning Java. So, let us program our first Program in Java AWT as Hello World using Labels and Frames.

Below is the implementation of the above method:

Java
// Java AWT Program for Hello World
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

// Driver Class
public class AWT_Example {
    // main function
    public static void main(String[] args)
    {
        // Declaring a Frame and Label
        Frame frame = new Frame("Basic Program");
        Label label = new Label("Hello World!");

        // Aligning the label to CENTER
        label.setAlignment(Label.CENTER);

        // Adding Label and Setting
        // the Size of the Frame
        frame.add(label);
        frame.setSize(300, 300);

        // Making the Frame visible
        frame.setVisible(true);

        // Using WindowListener for closing the window
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
    }
}

Running:

javac AWT_Example.java
java AWT_Example

Output:

Java AWT Hello World

2. Java AWT Program to create Button

Below is the implementation of the Java AWT Program to create a Button:

Java
// Java AWT Program for Button
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

// Driver Class
public class Button_Example {
    // main function
    public static void main(String[] args)
    {
        // Creating instance of frame with the label
        Frame frame = new Frame("Example 2");

        // Creating instance of button with label
        Button button = new Button("Click Here");

        // Setting the position for the button in frame
        button.setBounds(80, 100, 64, 30);

        // Adding button to the frame
        frame.add(button);

        // setting size, layout and visibility of frame
        frame.setSize(300, 300);
        frame.setLayout(null);
        frame.setVisible(true);

        // Using WindowListener for closing the window
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
    }
}

Running:

javac Button_Example.java
java Button_Example

Output:

Java AWT Button Output

Java AWT Tutorial – FAQs

1. What is AWT in Java? 

AWT stands for Abstract Window Toolkit, which is an API for creating graphical user interface (GUI) or windows-based applications in Java. AWT provides various components like buttons, labels, text fields, etc. that can be used as objects in a Java program

2. What are the advantages of AWT? 

Some of the advantages of AWT are:

  • It is easy to use and learn for beginners.
  • It is compatible with all platforms that support Java.
  • It provides a native look and feel for the components.

3. What are the types of containers in AWT? 

A container is a component that can contain other components. There are four types of containers in AWT:

  • Window: a container that has no borders and menu bars. It requires a frame, dialog, or another window to create it.
  • Panel: a container that has no title bar, border, or menu bar. It is a generic container for holding components.
  • Frame: a container that has a title bar, and border, and can have menu bars. It is the most widely used container for developing AWT applications.
  • Dialog: a container that has a title bar, and border, and can have buttons. It is used to display messages or get user input.

4. How to create and use components in AWT? 

To create and use components in AWT, we need to follow these steps:

  • Import the java.awt package, which contains the classes for AWT components.
  • Create an instance of the component class, such as Button, Label, TextField, etc.
  • Set the properties of the component, such as size, location, text, color, etc.
  • Add the component to a container, such as Frame, Panel, etc.
  • Set the visibility of the container to true.


Next Article

Similar Reads

Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.awt.image.RescaleOp Class in Java with Examples
RescaleOp is a class in java.awt.image package which implements BufferedImageOp and RasterOp interface. This class performs a pixel-by-pixel rescaling of the data in the source image by multiplying the sample values for each pixel by a scale factor and then adding an offset. The scaled sample values are clipped to the minimum/maximum representation
5 min read
Java AWT | GridLayout Class
GridLayout class represents a layout manager with a specified number of rows and columns in a rectangular grid. The GridLayout container is divided into an equal-sized of rectangles, and one of the components is placed in each rectangle. Every rectangle cell has the same size therefore, they contain a component, which fills the entire cell. When th
5 min read
Java AWT | Color Class
The Color class is a part of Java Abstract Window Toolkit(AWT) package. The Color class creates color by using the given RGBA values where RGBA stands for RED, GREEN, BLUE, ALPHA or using HSB value where HSB stands for HUE, SATURATION, BRIcomponents. The value for individual components RGBA ranges from 0 to 255 or 0.0 to 0.1. The value of alpha det
9 min read
Java AWT | MouseInfo and PointerInfo
MouseInfo and PointerInfo is a part of Java AWT. MouseInfo provides information about the location of the pointer and the number of buttons on the mouse. PointerInfo provides information returns the information about the location of the pointer and the graphics device. Methods of MouseInfo Method Explanation getNumberOfButtons() Returns the number
2 min read
Java AWT | Dimension Class
Dimension class is a part of Java AWT. It contains the height and width of a component in an integer as well as double precision. The use of Dimension class is that many functions of Java AWT and Swing return dimension object. Constructors of the Dimension class Dimension() : It will create a new Object with height and width set to zero.Dimension(D
4 min read
Java AWT | Canvas Class
Canvas class is a part of Java AWT. Canvas is a blank rectangular area where the user can draw or trap input from the user. Canvas class inherits the Component class.Constructor of the Canvas class are : Canvas(): Creates a new blank canvas.Canvas(GraphicsConfiguration c): Creates a new canvas with a specified graphics configuration. Commonly used
3 min read
Java AWT | Ellipse2D
Ellipse2D class is present in java.awt.geom package and it is used to define an ellipse by stating its framing rectangle. This class is only the abstract superclass for all objects which store a 2D ellipse. Ellipse2D.Double defines an ellipse with double precision. Ellipse2D.Float defines an ellipse with float precision. Constructor of the class ar
5 min read
Java AWT | WindowStateListener
WindowStateListener is a part of java.awt.event package. It is an interface to handle window state events. This interface returns an event when the frame or window associated with it is iconified or maximized.Abstract function of the class: windowStateChanged(WindowEvent e) : invoked when a state of the window is changed. Below programs illustrate
2 min read
Java AWT | FlowLayout
FlowLayout is used to arrange components in a sequence one after the other. The default layout of applet and panel is FlowLayout. Constructors : FlowLayout(): It will Construct a new FlowLayout with centered alignment.The horizontal and vertical gap will be 5 pixels. FlowLayout(int align) : It will Construct a new FlowLayout with given alignment.Th
5 min read
Java AWT | SpringLayout Class
A SpringLayout class in AWT(Abstract Window Toolkit) laid out of the children to its associated container, according to a set of Layout constraints. Each constraint is represented by a Spring object which controls the vertical or horizontal distance between two component edges. The edges can belong to any child of the container, or to the container
5 min read
Java AWT | GridBagLayout Class
GridBagLayout class is a flexible layout manager. It is used to aligns the components horizontally, vertically, or along their baseline. It doesn't require the components of the same size. Each GridBagLayout object manages a rectangular grid of cells, dynamic with each component occupying one or more cells, called its display area. GridBagLayout co
6 min read
Java AWT | BoxLayout Class
The BoxLayout class is used to arrange the components either vertically (along Y-axis) or horizontally (along X-axis). In BoxLayout class, the components are put either in a single row or a single column. The components will not wrap so, for example, a horizontal arrangement of components will stay horizontally arranged when the frame is resized. C
5 min read
Java AWT | MenuShortcut Class
MenuShortcut class is a part of JavaAWT. MenuShortcut class implements menu shortcuts which are implemented using virtual keycodes. The MenuShortcut class represents a keyboard accelerator for a MenuItem. Constructors of the class: MenuShortcut(int k): Creates a MenuShortcut object with specified key. MenuShortcut(int k, boolean b): Constructs a ne
5 min read
Java program to convert Currency using AWT
Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. Java swing components are lightweight, platform-in
4 min read
Java program to store a Student Information in a File using AWT
Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. Java swing components are lightweight, platform-in
4 min read
Difference between AWT and Swing in Java
Java is one of the most in-demand programming languages for developing a variety of applications. The popularity of Java can be attributed to its versatility as it can be used to design customized applications that are light and fast and serve a variety of purposes ranging from web services to android applications. Java is fast, reliable, and secur
2 min read
What is Java AWT Graphics?
Graphics is an abstract class provided by Java AWT which is used to draw or paint on the components. It consists of various fields which hold information like components to be painted, font, color, XOR mode, etc., and methods that allow drawing various shapes on the GUI components. Graphics is an abstract class and thus cannot be initialized direct
6 min read
Java AWT Label
Abstract Window Toolkit (AWT) was Java's first GUI framework, and it has been part of Java since version 1.0. It contains numerous classes and methods that allow you to create windows and simple controls. Controls are components that allow a user to interact with your application in various ways. The AWT supports the following types of controls: La
7 min read
Java AWT Toolkit
The Abstract Window Toolkit (AWT) is a Java package that provides a platform-indepеndеnt sеt of tools for creating graphical usеr intеrfacеs (GUIs). AWT is part of thе Java Foundation Classеs (JFC), which also includes Swing for morе advancеd GUI dеvеlopmеnt. In this rеsponsе, I'll providе an ovеrviеw of thе kеy componеnts and concеpts in AWT, alon
6 min read
Java AWT CheckboxGroup
Java AWT CheckboxGroup is a class that is used to create checkboxes and group a set of checkbox buttons together. Many components in the CheckboxGroup separate, which serves as a means to group a set of checkboxes. In this clause, we will delve into the CheckboxGroup class, and its methods, and demo its usage through a very simple example. Class De
3 min read
Java AWT Checkbox
Java AWT (Abstract Window Toolkit) provides a really various set of tools for edifice in writing user interfaces (GUIs), and among these tools is the Checkbox class. Checkboxes are necessary components for user interactions, allowing users to work binary choices easily. In this clause, we'll search the Checkbox class, its constructors, and methods,
4 min read
Java ItemListener in AWT
The Java ItemListener user interface in Java's Abstract Window Toolkit (AWT) is a crucial component for managing user interactions with elements like checkboxes and option lists. In this article, we wish to search how the ItemListener interface is old in AWT to respond to exploiter input. The ItemListener interface is divided into the java.awt.even
3 min read
Java MouseMotionListener in AWT
Java AWT (Abstract Window Toolkit) provides varied event listeners to wield exploiter interactions. One of these is the Java MouseMotionListener, which is secondhand to track sneak out motion events. This hearer allows you to respond to the mouse's front, such as sleuthing when the mouse is dragged or moved within a component. In this clause, we wi
3 min read
Java KeyListener in AWT
The Java KeyListener in the Abstract Window Toolkit (AWT) is a fundamental tool for achieving this. The KeyListener Interface is found in "java.awt.event" package. In this article, we'll explore what the KeyListener is, and its declaration methods, and supply examples with explanatory comments. Java KeyListener in AWTThe KeyListener port in Java AW
3 min read
Java AWT Panel
In Java's Abstract Window Toolkit (AWT), the Panel class is a fundamental component for creating graphical user interfaces. It offers a straightforward way to organize and group various GUI elements. This article explores the Panel class in Java AWT, covering its essential aspects, methods, and constructors, and demonstrating its practical use thro
2 min read
Java AWT PopupMenu
In Java, AWT (Abstract Window Toolkit) provides a PopupMenu course that allows you to make pop-up menus in your graphical user port (GUI) applications. A PopupMenu is a setting menu that appears when you right-click on a component, such as a button or a venire. It provides a set of options or actions that the user can select from. In this clause, w
3 min read
Java MouseListener in AWT
The Abstract Window Toolkit (AWT) in Java provides a collection of user interface components and event-handling features for creating graphical user interfaces (GUIs). User interaction is an important component of GUI programming, and the MouseListener interface in AWT is an important tool for managing mouse events in Java applications. In this art
3 min read
Java ActionListener in AWT
The Java Abstract Window Toolkit (AWT) is a GUI framework that provides a set of classes and methods for creating and managing user interfaces in Java applications. One of the most important components in AWT is the ActionListener interface. It is a key element for adding interactivity in Java applications by handling user actions. In this article,
4 min read
Java AWT MenuItem & Menu
Java Abstract Window Toolkit (AWT) provides a comprehensive set of classes and methods to create graphical user interfaces. In this article, we will explore the MenuItem and Menu classes, which are essential for building menus in Java applications. Java AWT MenuItemMenuItem is a class that represents a simple labeled menu item within a menu. It can
3 min read
Practice Tags :