Java AWT Examples
Here are some Java AWT examples:
- Hello World in Java AWT
- Java AWT Program to create Button
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 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:
2. Java AWT Program to create Button
Below is the implementation of the Java AWT Program to create a Button:
// 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 Tutorial
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.
Contact Us