The following code shows some Examples of AWT in Java.


You can create a Java application using AWT to add labels, buttons, text fields, lists, and other components to a graphical user interface (GUI). The following code shows an example of how to do it.

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

public class AWTComponentsDemo extends Frame {
    private Label label;
    private TextField textField;
    private Button button;
    private List list;

    public AWTComponentsDemo() {
        setTitle("AWT Components Demo");
        setSize(400, 300);
        setLayout(new FlowLayout());
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        label = new Label("Label:");
        add(label);

        textField = new TextField(20);
        add(textField);

        button = new Button("Click Me");
        add(button);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String text = textField.getText();
                list.add(text);
                textField.setText("");
            }
        });

        list = new List(5);
        add(list);

        setVisible(true);
    }

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

In this program:

  1. We create an AWTComponentsDemo class that extends Frame to create the main window.
  2. Inside the constructor:
    • We set the title, size, layout manager, and close operation for the frame.
    • We add a WindowListener to handle window-closing events.
  3. Then, we create various AWT components and add them to the frame:
    • Label: Displays a static text label.
    • TextField: Allows user input.
    • Button: Triggers an action when clicked.
    • List: Displays a list of items.
  4. After that, we add an ActionListener to the button to handle its click event. When the button is clicked, it reads the text from the text field, adds it to the list, and clears the text field.
  5. Finally, we make the frame visible.

Compile and run this program to see how it adds labels, buttons, text fields, and lists to a simple AWT-based GUI.


Further Reading

Spring Framework Practice Problems and Their Solutions

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

Java Practice Exercise

programmingempire

Princites