Java AWT GUI Development and OOP Inheritance

Posted by Anonymous and classified in Computers

Written on in English with a size of 7.41 KB

Building Java GUI Applications with AWT

Creating GUI applications using Abstract Window Toolkit (AWT) involves setting up a top-level container, adding components, arranging them with a Layout Manager, and making the container visible.

Steps to Create an AWT Application

1. Choose a Top-Level Container

The application needs a primary window to hold all components. The most common choice is the Frame class, which provides a title bar, borders, and window controls.

import java.awt.*;

// Class extends Frame to be the application window itself
public class AWTExample extends Frame {
    // Constructor and other methods
}

2. Initialize the Container (The Frame)

Inside the constructor, you set up the basic properties of the window:

  • Title: Set the window title.
  • Size: Define the initial dimensions.
  • Visibility: Make the window appear on the screen.
public AWTExample() {
    // 1. Set the layout manager
    // FlowLayout places components left-to-right.
    setLayout(new FlowLayout());

    // 2. Set the title of the frame
    setTitle("My Simple AWT GUI");

    // 3. Set the size (width, height)
    setSize(400, 200);

    // 4. Make the frame visible
    setVisible(true);
}

3. Add Components

Instantiate and add UI components (controls) to the container. AWT components are located in the java.awt package.

// Inside the AWTExample constructor:
Label myLabel = new Label("Enter Name:");
TextField myTextField = new TextField(20); // 20 columns wide
Button myButton = new Button("Submit");

// Add the components to the Frame
add(myLabel);
add(myTextField);
add(myButton);

4. Arrange Components using Layout Managers

A Layout Manager is an object associated with a container that controls the size and position of the components within it. If you do not set one, the default layout (usually BorderLayout for Frame) is used.

Layout ManagerDescriptionExample Use
FlowLayoutComponents flow left to right, wrapping as needed.Simple forms, toolbars.
BorderLayoutPlaced in five regions: North, South, East, West, and Center.Standard application layouts.
GridLayoutArranged in a grid of equal-sized cells.Calculators, tables.
// Example: Setting a BorderLayout
setLayout(new BorderLayout());
add(new Button("North"), BorderLayout.NORTH);

5. Implement Event Handling

Without event handling, the GUI will not respond to user interaction. You must implement the Delegation Event Model by registering listeners.

// Implement the ActionListener interface
class ButtonHandler implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        // This code runs when the button is clicked
        System.out.println("Button Clicked!");
    }
}

// In the AWTExample constructor:
ButtonHandler handler = new ButtonHandler();
myButton.addActionListener(handler);

6. Handle Window Closing

AWT Frames do not close by default when the 'X' button is clicked. You must explicitly handle the WindowEvent using the WindowAdapter class.

// In the AWTExample constructor:
addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent we) {
        System.exit(0); // Terminate the application
    }
});

Complete AWT Example Code

import java.awt.*;
import java.awt.event.*;

public class AWTExample extends Frame {
    public AWTExample() {
        setTitle("AWT Demo");
        setSize(300, 150);
        setLayout(new FlowLayout());

        Label welcomeLabel = new Label("Welcome to AWT!");
        Button clickButton = new Button("Click Me");
        add(welcomeLabel);
        add(clickButton);

        clickButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                welcomeLabel.setText("Button Was Clicked!");
            }
        });

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });

        setVisible(true);
    }

    public static void main(String[] args) {
        new AWTExample();
    }
}

Understanding Inheritance in Object-Oriented Programming

Inheritance is a fundamental concept in Object-Oriented Programming (OOP) where a new class (the subclass or derived class) is created from an existing class (the superclass or base class). The subclass inherits the properties and behaviors of its superclass, allowing for code reusability and establishing an "is-a" relationship.

Types of Inheritance

  • Single Inheritance: A class inherits from only one base class (e.g., Class B inherits from Class A).
  • Multilevel Inheritance: A class inherits from a derived class, creating a chain (e.g., ABC).
  • Hierarchical Inheritance: Multiple classes inherit from a single base class (e.g., Class B and Class C both inherit from A).
  • Hybrid Inheritance: A combination of two or more types of inheritance.
  • Multiple Inheritance: A class inherits from more than one base class. This is often restricted in languages like Java to avoid the "Deadly Diamond of Death" ambiguity.

Multiple Inheritance Using Interfaces

Languages like Java and C# do not support multiple inheritance directly through classes to avoid complexity. However, they achieve this functionality through Interfaces.

What is an Interface?

An interface is a blueprint of a class containing only abstract methods and constant fields. A class can implement multiple interfaces, effectively inheriting the contracts from multiple sources.

Java Multiple Inheritance Example

// Interface 1
interface Parent1 {
    void methodP1();
}

// Interface 2
interface Parent2 {
    void methodP2();
}

// Child class implements both interfaces
class Child implements Parent1, Parent2 {
    @Override
    public void methodP1() {
        System.out.println("Child implements method from Parent1.");
    }

    @Override
    public void methodP2() {
        System.out.println("Child implements method from Parent2.");
    }

    public void uniqueChildMethod() {
        System.out.println("Child's own unique method.");
    }
}

public class MultipleInheritanceDemo {
    public static void main(String[] args) {
        Child obj = new Child();
        obj.methodP1();
        obj.methodP2();
        obj.uniqueChildMethod();
    }
}

Output:

Child implements method from Parent1.
Child implements method from Parent2.
Child's own unique method.

Related entries: