Java AWT is a powerful toolkit for creating graphical user interfaces (GUIs) in Java applications. It provides a set of native components for building windows, buttons, text fields, and other UI elements.
AWT offers various components for constructing user interfaces:
Here's a basic example of creating an AWT window:
import java.awt.*;
public class SimpleWindow extends Frame {
public SimpleWindow() {
setTitle("My First AWT Window");
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new SimpleWindow();
}
}
Let's create a window with a button and a label:
import java.awt.*;
public class ComponentExample extends Frame {
public ComponentExample() {
setTitle("AWT Components");
setSize(300, 200);
setLayout(new FlowLayout());
Button button = new Button("Click Me");
Label label = new Label("Hello, AWT!");
add(button);
add(label);
setVisible(true);
}
public static void main(String[] args) {
new ComponentExample();
}
}
AWT uses an event-driven programming model. Components generate events, and listeners respond to them. Here's how to handle a button click:
import java.awt.*;
import java.awt.event.*;
public class EventExample extends Frame implements ActionListener {
private Label label;
public EventExample() {
setTitle("AWT Event Handling");
setSize(300, 200);
setLayout(new FlowLayout());
Button button = new Button("Click Me");
button.addActionListener(this);
label = new Label("No clicks yet");
add(button);
add(label);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
label.setText("Button clicked!");
}
public static void main(String[] args) {
new EventExample();
}
}
While AWT is powerful, it has some limitations:
For more advanced GUI development, consider using Java Swing, which offers a richer set of components and platform-independent rendering.
Java AWT provides a foundation for creating graphical user interfaces in Java. While it's not as feature-rich as newer frameworks like Swing or JavaFX, understanding AWT is valuable for grasping the basics of GUI programming in Java.
For more advanced Java topics, explore Java Multithreading or Java Networking Classes.