Home »
Java programming language
Java AWT Frame
Java | AWT Frame: In this tutorial, we will look at one of the Java AWT components, the AWT Frame with example.
Submitted by Saranjay Kumar, on April 29, 2020
Creating a frame is one of the most elementary steps in designing any GUI application. Almost in all cases we will place components in a frame. There are two ways to create a frame.
- Extend the frame class
- Make a frame object
There are some methods associated with a frame class that are used to set its properties.
- public void setLayout(LayoutManager lm) – It is used to set the layout that a frame uses. A layout basically dictates the position of various components that are placed in it.
- public void setSize(int width, int height) – It is used to set the intial size of the frame.
- public void setVisible(boolean visibility) – It is used to set the visibility of the frame. It must be set to true for the frame (and the various components placed in it) to be visible on the screen.
- public void add (Component c) – It is used to place/add the components in the frame.
Let us see how to use these various methods. We design a simple frame and place a button and a label on the screen.
1. Extend the Frame class
Consider the following code -
import java.awt.*;
public class CreateFrame extends Frame {
CreateFrame() {
Button b1 = new Button("Click me!");
Label l1 = new Label("Label");
b1.setBounds(50, 50, 100, 50);
l1.setBounds(50, 100, 100, 50);
setLayout(null);
setSize(300, 300);
setVisible(true);
add(b1);
add(l1);
}
public static void main(String[] args) {
CreateFrame f = new CreateFrame();
}
}
In this code, the CreateFrame class extends the Frame class. So we dont need to explicitly make an object of frame class. Methods like add() and setVisible() are automatically called on the CreateFrame class.
2. Make an object of Frame class
Consider the following code -
import java.awt.*;
public class CreateFrame {
public static void main(String[] args) {
Frame f = new Frame();
Button b1 = new Button("Click me!");
Label l1 = new Label("Label");
b1.setBounds(50, 50, 100, 50);
l1.setBounds(50, 100, 100, 50);
f.setLayout(null);
f.setSize(300, 300);
f.setVisible(true);
f.add(b1);
f.add(l1);
}
}
In this code, we explicitly create an object of the Frame class and all methods are called on this object.
Output: In both cases, we get the same output