× back
Next Topic → ← Previous Topic

Applet

Applet Hierarchy

Object → Component → Container → Panel → Applet

Applet Life Cycle

The Applet Life Cycle refers to the series of phases an applet goes through during its complete execution.

init Method

                    
public void init()
                    
                
  • The init method is crucial for initializing the applet, allowing tasks such as variable initialization, setting background and foreground colors, and allocating memory for controls (e.g., labels, checkboxes).
  • This method is executed only once during the entire life cycle of the applet.
  • When the applet is first loaded into memory, the init method is called.

start Method

                    
public void start()
                    
                
  • The start method is executed after the init method.
  • Useful for restarting an applet if its execution has been stopped.
  • Restarting the execution of the current webpage is achieved using the start method.
  • There's no predictable limit to how many times an applet webpage can be restarted; it can be restarted multiple times.
  • Whenever switching back to the same page, the start method will be executed again.
  • When we click on the maximize button than this method can be called.

paint Method

                    
public void paint(Graphics g)
                    
                
  • The paint method is used to display content in the view area of the applet.
  • With the Graphics class, one can paint shapes like circles and rectangles, as well as display text within the applet.
  • This method is executed after the start method.

stop Method

                    
public void stop()
                    
                
  • The stop method is employed to halt the execution of an applet.
  • Execution of the current webpage is stopped using the stop method when transitioning from one webpage to another. Additionally, clicking the minimize button on the applet window triggers the execution of the stop method.

destroy Method

                    
public void destroy()
                    
                
  • The destroy method serves to release the applet object's memory. When this method is called, the applet memory is destroyed, making it available for use in other programs.
  • Clicking on the cross button of the applet window triggers the execution of the destroy method.
  • The destroy method is executed only once in the entire life cycle of an applet.
  • It's worth noting that the init and destroy methods are executed only once, whereas the remaining methods can be executed multiple times.

Note: Given that Java applets have been deprecated, investing time in learning them is no longer considered practical or beneficial. Applets have fallen out of favor due to security concerns and the evolution of web technologies. Consequently, we recommend focusing on more contemporary and versatile alternatives for creating graphical user interfaces (GUIs).

One such alternative is Swing, a robust GUI toolkit for Java. Swing provides a set of components and tools that allow developers to create interactive and visually appealing graphical interfaces for desktop applications. By learning Swing, you'll gain valuable skills in building modern and responsive user interfaces that align with current industry standards.

Swing offers a wide range of components, including buttons, text fields, panels, and more, making it suitable for developing diverse applications with varying complexity. Moreover, Swing applications can run independently of web browsers, providing greater flexibility in deployment.

Graphical User Interface using AWT

AWT, which stands for Abstract Window Toolkit, is a set of classes in Java that provides the foundation for creating Graphical User Interfaces (GUIs). AWT facilitates the development of applications with GUI components, allowing developers to build interactive and user-friendly software.

Frame

The Frame class in AWT represents the main window or container for a GUI application. It serves as the top-level container that holds and organizes other GUI components. To use Frame, you need to import it with:

                    
import java.awt.Frame;
                    
                

Label

The Label class is used to display text related to a text field or to denote the purpose of the following GUI elements. Labels are passive controls, meaning user interaction is not possible with labels, unlike active controls such as text fields or checkboxes. To use Label, you need to import it with:

                    
import java.awt.Label;
                    
                

Constructors of the Label class:

The Label class is part of the Component class in the AWT package. It provides three constructors:

  1. Label(): Creates an empty label.
  2. Label(String text): Creates a label with the specified text, left-justified.
  3. Label(String text, Alignment): Creates a label with specified text and alignment. Possible alignments are left, right, and center.

So till now we have learnt about Label and Frame so let's make a simple program using that.

                    
// Import necessary AWT classes
import java.awt.Frame;
import java.awt.Label;
import java.awt.FlowLayout; // using this components comes one after another

// Main class for the AWT GUI program
public class TestStuff {

    // Main method, the entry point of the program
    public static void main(String[] args) {
        // Create a Frame (main window) with a title
        Frame frame = new Frame("Simple AWT Program");
        FlowLayout flow1 = new FlowLayout();

        frame.setLayout(flow1);

        // Create a Label with specified text
        Label label = new Label("Hello, AWT!");

        // Set the layout of the frame to null (absolute layout)
        frame.setLayout(null);

        // Set the bounds (position and size) for the label
        label.setBounds(50, 50, 100, 30);

        // Add the label to the frame
        frame.add(label);

        // Set the size of the frame
        frame.setSize(300, 200);

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

    }
}
                    
                

Button

Buttons play a crucial role in user interfaces, providing a means to trigger actions or submit data in a form. They are fundamental components for user interaction in graphical applications.

  • Usage: Buttons are commonly employed to submit the details entered in a form, initiate specific actions, or respond to user inputs.
  • Constructors of the Button class:
  1. Button(): This constructor creates an empty button, meaning a button with no visible label displayed on it. It serves as a blank canvas for customization based on application needs.

                                        
    Button emptyButton = new Button();
                                        
                                    
  2. Button(String text): This constructor creates a button with the specified string text as its label. The label provides a descriptive element to convey the purpose or action associated with the button.

                                        
    Button labeledButon = new Button("Click Me");
                                        
                                    

TextField

The TextField class in Java is utilized to create a single-line text box, offering a user-friendly way to input and retrieve textual information in graphical applications.

  • Usage: TextFields are commonly employed to gather user input, such as usernames, passwords, or other textual data, in a simple and intuitive manner.
  • Constructors of the TextField class:
  1. TextField(): This constructor creates a default text field with an initial width, allowing users to input text. It's a straightforward text box with no predefined text content.

                                    
    TextField defaultTextField = new TextField();
                                    
                                
  2. TextField(int col): The constructor with an integer parameter defines the width of the text field, specifying the number of columns it can display. This allows for customization based on the desired visual appearance.

                                    
    TextField customWidthTextField = new TextField(20);
                                    
                                
  3. TextField(String str): This constructor creates a text field with the specified initial text content. It's useful when you want to provide users with a predefined value or placeholder text.

                                    
    TextField preFilledTextField = new TextField("Enter your text here");
                                    
                                
  4. TextField(String str, int col): Combining both parameters, this constructor allows you to set both the initial text content and the width of the text field simultaneously, offering flexibility in customization.

                                
    TextFiel{d customTextField = new TextField("Default Text", 15);}
                                
                               

Now we are familiar with few AWT components, so now we will try to create the following window:

                    
import java.awt.*;
class Test
{
    public static void main(String[] args)
    {
        Frame frame = new Frame("New Window");
        FlowLayout fl = new FlowLayout();
        Label lab1 = new Label("Name : ");
        Label lab2 = new Label("Password : ");
        TextField tf1 = new TextField(20);
        TextField tf2 = new TextField(20);
        Button btn1 = new Button("Submit");

        frame.add(lab1);
        frame.add(tf1);
        frame.add(lab2);
        frame.add(tf2);
        frame.add(btn1);

        frame.setLayout(fl);
        frame.setVisible(true);
        frame.setSize(300, 200);
    }
}
                    
                

Event Handling In Java OR Delegation Event Model in Java

Event handling in Java, also known as the Delegation Event Model, enables the response to user actions on graphical user interface (GUI) components. Events represent user interactions like button clicks, key presses, or mouse movements, triggering specific actions in a Java program.

Now, let's create a simple Java program to demonstrate event handling using a button. In this example, we'll use an ActionListener to handle button click events. The comments in the code explain each part of the program.

                    
import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class EventHandlingExample {
    public static void main(String[] args) {
        Frame frame = new Frame("Event Handling Example");

        // Create a button
        Button button = new Button("Click Me");

        // Add an ActionListener to the button
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // This method is called when the button is clicked
                System.out.println("Button Clicked!");
            }
        });

        // Set layout to null for absolute positioning
        frame.setLayout(null);

        // Set bounds for the button
        button.setBounds(50, 50, 80, 30);

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

        // Set size of the frame
        frame.setSize(300, 200);

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

        // Add a WindowListener to handle closing the frame
        frame.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                System.exit(0);
            }
        });
    }
}
                    
                

In this program, the ActionListener is implemented to handle the button click event. When the button is clicked, the actionPerformed method is executed, and it prints a message to the console. The program creates a simple frame with a button, and the event handling logic is encapsulated within the ActionListener.

Adapter Classes

Adapter classes in Java are designed to address the limitations of interfaces. In interfaces, all methods are abstract, meaning that the implementing class must provide definitions for all declared methods. This can be cumbersome when we are only interested in a subset of the methods. Adapter classes offer a solution to this issue by providing empty implementations for all methods in an interface.

Now, let's create a simple Java program to demonstrate the use of an adapter class for event handling. This example will use a MouseListener and its corresponding adapter class, MouseAdapter. The comments in the code explain each part of the program.

                
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class AdapterExample {
    public static void main(String[] args) {
        Frame frame = new Frame("Adapter Example");
        Label label = new Label("Mouse Event Demo");

        // Create a custom mouse listener by extending MouseAdapter
        CustomMouseListener customMouseListener = new CustomMouseListener();

        // Add the custom mouse listener to the label
        label.addMouseListener(customMouseListener);

        // Set layout to null for absolute positioning
        frame.setLayout(null);

        // Set bounds for the label
        label.setBounds(50, 50, 150, 30);

        // Add the label to the frame
        frame.add(label);

        // Set size of the frame
        frame.setSize(300, 200);

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

        // Add a WindowListener to handle closing the frame
        frame.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                System.exit(0);
            }
        });
    }

    // Custom mouse listener class extending MouseAdapter
    static class CustomMouseListener extends MouseAdapter {
        // Override only the methods you need
        public void mouseClicked(MouseEvent e) {
            // Custom handling for mouse click
            System.out.println("Mouse Clicked!");
        }
    }
}
                
            

In this program, the CustomMouseListener class extends MouseAdapter to provide an empty implementation for the mouseClicked method. This allows you to only override the methods you need for your specific use case.

Swing Introduction

Swing is a powerful GUI (Graphical User Interface) toolkit in Java designed to overcome the limitations of AWT (Abstract Window Toolkit). It provides a set of classes that offers more flexibility and advanced GUI components for developing both window and web applications.

Differences between AWT and Swing:

When working with Swing components in Java, you need to import classes from the javax.swing package. Below is a simple example that demonstrates how to create a basic Swing window using JFrame.

                    
import javax.swing.*;

public class EmptySwingWindow {
    public static void main(String[] args) {
        // Create a JFrame (window)
        JFrame frame = new JFrame("Empty Swing Window");

        // Set default close operation and make the frame visible
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}
                    
                

Swing Component: JLabel Class

The JLabel class in Swing is used to display a line of text or an image. It is similar to the AWT Label but with some enhancements and added features.

For example, in a login form like Gmail, the "Enter your email" and "Enter your password" messages are similar to labels. In Swing, these labels are instances of the JLabel class.

The key difference between AWT Label and Swing JLabel is the naming convention; in AWT, it was Label, and in Swing, it is JLabel.

Constructors of JLabel class:

  • JLabel(): Creates a JLabel with no text.
  • JLabel(String text): Creates a JLabel with the specified text.
  • JLabel(Icon icon): Creates a JLabel that displays the specified icon (image). Useful when you want to represent information with images.
                            
import javax.swing.*;
import java.awt.*;

public class JLabelExample {
    public static void main(String[] args) {
        // Create a JFrame (window)
        JFrame frame = new JFrame("JLabel Example");

        // Create a JLabel with text
        JLabel textLabel = new JLabel("Hello, Swing!");

        // Create a JLabel with an icon (image)
        ImageIcon icon = new ImageIcon("path/to/your/image.png");
        JLabel iconLabel = new JLabel(icon);

        // Add labels to the content pane
        Container container = frame.getContentPane();
        container.setLayout(new FlowLayout());
        container.add(textLabel);
        container.add(iconLabel);

        // Set default close operation and make the frame visible
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}
                            
                        

Swing Component: JTextField Class

The JTextField class in Swing is used to create a single-line text input field. It allows users to enter and edit text. JTextField provides a versatile way to handle user input in graphical user interfaces.

Key features of JTextField:

  • Allows users to input and edit a single line of text.
  • Can be used for various purposes, such as accepting usernames, passwords, or search queries.
  • Provides events to listen for changes in the text.

Constructors of JTextField class:

  • JTextField(): Creates an empty text field.
  • JTextField(String text): Creates a text field with the specified initial text.
  • JTextField(int columns): Creates a text field with the specified number of columns (width).
                            
import javax.swing.*;
import java.awt.*;

public class JTextFieldExample {
    public static void main(String[] args) {
        // Create a JFrame (window)
        JFrame frame = new JFrame("JTextField Example");

        // Create a JTextField
        JTextField textField = new JTextField("Type here...");

        // Add the text field to the content pane
        Container container = frame.getContentPane();
        container.setLayout(new FlowLayout());
        container.add(textField);

        // Set default close operation and make the frame visible
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}
                            
                        

Swing Component: JTextArea Class

The JTextArea class in Swing is used to create a multi-line text area that allows users to input and edit text over multiple lines. It is suitable for handling larger amounts of text compared to a single-line text field like JTextField.

Key features of JTextArea:

  • Allows users to input and edit text over multiple lines.
  • Useful for scenarios where a larger amount of text input is required, such as comments or descriptions.
  • Supports scrolling for viewing and editing longer text.
  • Provides events to listen for changes in the text.

Constructors of JTextArea class:

  • JTextArea(): Creates an empty text area.
  • JTextArea(String text): Creates a text area with the specified initial text.
  • JTextArea(int rows, int columns): Creates a text area with the specified number of rows and columns.
                            
import javax.swing.*;
import java.awt.*;

public class JTextAreaExample {
    public static void main(String[] args) {
        // Create a JFrame (window)
        JFrame frame = new JFrame("JTextArea Example");

        // Create a JTextArea
        JTextArea textArea = new JTextArea("Type here...");

        // Set the rows and columns for the text area
        textArea.setRows(5);
        textArea.setColumns(20);

        // Add the text area to a JScrollPane for scrolling
        JScrollPane scrollPane = new JScrollPane(textArea);

        // Add the scroll pane to the content pane
        Container container = frame.getContentPane();
        container.setLayout(new FlowLayout());
        container.add(scrollPane);

        // Set default close operation and make the frame visible
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}
                            
                        

Swing Component: JButton Class

The JButton class in Swing is used to create a button that can trigger an action when clicked. Buttons are fundamental components for user interaction in graphical user interfaces, allowing users to perform various tasks or operations.

Key features of JButton:

  • Represents a clickable button.
  • Can be used to trigger events or actions in response to user clicks.
  • Supports text, icons, or both as content.
  • Provides events to listen for button clicks.

Constructors of JButton class:

  • JButton(): Creates a button with no text or icon.
  • JButton(String text): Creates a button with the specified text.
  • JButton(Icon icon): Creates a button with the specified icon.
                            
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JButtonExample {
    public static void main(String[] args) {
        // Create a JFrame (window)
        JFrame frame = new JFrame("JButton Example");

        // Create a JButton
        JButton button = new JButton("Click Me");

        // Add an ActionListener to handle button clicks
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "Button Clicked!");
            }
        });

        // Add the button to the content pane
        Container container = frame.getContentPane();
        container.setLayout(new FlowLayout());
        container.add(button);

        // Set default close operation and make the frame visible
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}
                            
                        

Swing Component: JPasswordField Class

The JPasswordField class in Swing is used to create a text input field specifically designed for entering passwords. It provides a secure way to handle sensitive information, such as user passwords, by displaying the entered characters as dots or asterisks.

Key features of JPasswordField:

  • Allows users to input and edit text (passwords) in a secure manner.
  • Displays characters as dots or asterisks for privacy.
  • Provides events to listen for changes in the entered password.

Constructors of JPasswordField class:

  • JPasswordField(): Creates an empty password field.
  • JPasswordField(int columns): Creates a password field with the specified number of columns (width).
                            
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JPasswordFieldExample {
    public static void main(String[] args) {
        // Create a JFrame (window)
        JFrame frame = new JFrame("JPasswordField Example");

        // Create a JPasswordField
        JPasswordField passwordField = new JPasswordField();

        // Create a JButton to simulate checking the password
        JButton checkButton = new JButton("Check Password");

        // Add an ActionListener to handle button clicks
        checkButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                char[] password = passwordField.getPassword();
                // For demonstration purposes, convert the password to a string and show in a dialog
                String passwordString = new String(password);
                JOptionPane.showMessageDialog(frame, "Entered Password: " + passwordString);
            }
        });

        // Add the password field and button to the content pane
        Container container = frame.getContentPane();
        container.setLayout(new FlowLayout());
        container.add(passwordField);
        container.add(checkButton);

        // Set default close operation and make the frame visible
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}
                            
                        

Programs

Simple calculator program using AWT

                            
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TestStuff implements ActionListener {
    TextField tf1, tf2, tf3;
    Button b1, b2, b3, b4, b5;

    public TestStuff() {
        Frame mainF = new Frame("Simple calculator");
        FlowLayout ef1 = new FlowLayout();
        Label el1 = new Label("Enter First Number : ");
        Label el2 = new Label("Enter Second Number : ");
        tf1 = new TextField(10);
        tf2 = new TextField(10);
        b1 = new Button("Add");
        b2 = new Button("Sub");
        b3 = new Button("Mult");
        b4 = new Button("Div");
        b5 = new Button("Reset");
        tf3 = new TextField(10);

        mainF.setLayout(ef1);

        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
        b4.addActionListener(this);
        b5.addActionListener(this);

        mainF.add(el1);
        mainF.add(tf1);
        mainF.add(el2);
        mainF.add(tf2);
        mainF.add(b1);
        mainF.add(b2);
        mainF.add(b3);
        mainF.add(b4);
        mainF.add(b5);
        mainF.add(tf3);

        mainF.setVisible(true);
        mainF.setSize(400, 200);
    }

    public void actionPerformed(ActionEvent e) {
        int num1 = Integer.parseInt(tf1.getText());
            int num2 = Integer.parseInt(tf2.getText());
            int num3 = 0;
        if (e.getSource() == b1) {
            num3 = num1 + num2;
            tf3.setText(String.valueOf(num3));
        }
        if(e.getSource() == b2) {
            num3 = num1 - num2;
            tf3.setText(String.valueOf(num3));
        }
        if(e.getSource() == b3) {
            num3 = num1 * num2;
            tf3.setText(String.valueOf(num3));
        }
        if(e.getSource() == b4) {
            num3 = num1 / num2;
            tf3.setText(String.valueOf(num3));
        }
        if(e.getSource() == b5) {
            tf1.setText("");
            tf2.setText("");
            tf3.setText("");
        }
    }

    public static void main(String[] args) {
        TestStuff one = new TestStuff();
    }
}
                            
                        

Simple calculator program using Swing

                            
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TestStuff implements ActionListener {
    private JTextField tf1, tf2, tf3;

    public TestStuff() {
        JFrame mainFrame = new JFrame("Simple Calculator");
        mainFrame.setLayout(new FlowLayout());
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel label1 = new JLabel("Enter First Number:");
        JLabel label2 = new JLabel("Enter Second Number:");
        tf1 = new JTextField(10);
        tf2 = new JTextField(10);

        JButton addButton = new JButton("Add");
        JButton subButton = new JButton("Sub");
        JButton multButton = new JButton("Mult");
        JButton divButton = new JButton("Div");
        JButton resetButton = new JButton("Reset");

        tf3 = new JTextField(10);
        tf3.setEditable(false);

        addButton.addActionListener(this);
        subButton.addActionListener(this);
        multButton.addActionListener(this);
        divButton.addActionListener(this);
        resetButton.addActionListener(this);

        mainFrame.add(label1);
        mainFrame.add(tf1);
        mainFrame.add(label2);
        mainFrame.add(tf2);
        mainFrame.add(addButton);
        mainFrame.add(subButton);
        mainFrame.add(multButton);
        mainFrame.add(divButton);
        mainFrame.add(resetButton);
        mainFrame.add(tf3);

        mainFrame.setSize(400, 200);
        mainFrame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        try {
            int num1 = Integer.parseInt(tf1.getText());
            int num2 = Integer.parseInt(tf2.getText());
            int num3 = 0;

            if (e.getActionCommand().equals("Add")) {
                num3 = num1 + num2;
            } else if (e.getActionCommand().equals("Sub")) {
                num3 = num1 - num2;
            } else if (e.getActionCommand().equals("Mult")) {
                num3 = num1 * num2;
            } else if (e.getActionCommand().equals("Div")) {
                num3 = num1 / num2;
            } else if (e.getActionCommand().equals("Reset")) {
                tf1.setText("");
                tf2.setText("");
                tf3.setText("");
                return; // Skip setting the result field for Reset button
            }

            tf3.setText(String.valueOf(num3));
        } catch (NumberFormatException | ArithmeticException ex) {
            tf3.setText("Error");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new TestStuff());
    }
}