Java Examples - Awt Frame Window

Updated on July 24, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 Yrs. I like playing video games & reading books.

1. About AWT Frame

The AWT Frame is a Top-Level window which can host other child controls on it. A Frame can have a Title Window with Minimize, Maximize and Close buttons. The default layout of the AWT Frame is BorderLayout. In this example, we will create a Frame Window at run time with two labels in it.

2. Required Imports

First, we create a file called FrameWin.java and in this we will create our own Frame which is derived from java.awt.Frame. Below are the required import statements. We will see the usage of each class when the article progress.

import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

3. Set the Frame Title and Layout

First, we create a class called FrameWin and derive it from the AWT Frame. In our constructor, we take the Frame Title as a string and pass that to the base class constructor by calling super(). Next, we change the default BorderLayout to FlowLayout so that the Labels we will add get seated side-by-side. In addition, The SetLayout() function is used to change the default layout. The below depiction explains Title and FlowLayout.

Notepad vs FlowLayout
Notepad vs FlowLayout | Source

We can map the notepad title to the Java Frame’s title. In the same way when can map the FlowLayout with how each typed letter appear in the Notepad. When we type, each character flow from left to right and when there is no room in the current line, the next letter appears in the leftmost edge of a next line of the screen. Now, imaging each letter as control occupying space in the Frame Window, we can get a picture how each control laid out in the Frame Window. Below is the code:

public class FrameWin 
extends Frame 
implements WindowListener {
    //Sample 01: Constructor
    public FrameWin(String FrameTitle){
        //Sample 02: Set Layout and Title
        super(FrameTitle);
        setLayout(new FlowLayout());

4. Add Labels to the Frame

As already told, a Frame window holds other child controls. The add() method is used to add child controls to the Frame. In our example, we are creating two label controls called L1 and L2. Then, we are adding that to the AWT Frame. Now, look at the depiction below:

Flow Layout and Labels
Flow Layout and Labels | Source

Here, when we add to three Label Controls one-by-one, the third control automatically goes to the second line as there is no space for it in the first line. This kind of automatic arrangement is what called Flow Layout. Now, look at the code below which shows how we add the Label controls to Frame.

//Sample 03: Create Two Labels
Label L1 = new Label("Label 1");
Label L2 = new Label("Label 2");

//Sample 04: Add Label to the 
//          Frame Window
add(L1);
add(L2);

5. Setting the Size and Position of Frame

Note that we created the Frame when we made a call to the super(). Because, we called the base class constructor with string title and that constructed the Frame for us. Next, we added the labels and at this stage our Frame is ready.

We should set a position and size to our Frame. The size not only sets the width and height of the Frame but also helps in laying out the labels according the Flow Layout. On the other hand, the position tells where the Frame should appear. Have a look at the below depiction:

Size and Position of AWT Frame
Size and Position of AWT Frame | Source

In the above picture, the black markers show the Frame width and height. The white markers show where the window will be positioned relative to the Top-Left corner of the desktop window. Now, have a look at the below code:

//Sample 05: Set Size of the Frame
setSize(400, 300);
setLocation(100,100);

6. Implementing WindowListener to Close the Frame

We derived our FrameWin class from java.awt.Frame and also claimed we will implement WindowListener. Java Framework calls the WindowListener functions when a window event takes place. For example, when a user minimize a window, Java calls windowIconified method. First, one need to tell the Frame that they are interested in responding to the window events by registering the Listener to it. We call the addWindowListener method and pass our FrameWin itself as a Listener since we will implement the WindowListener interface functions in it. Below is the code which adds the WindowListener to the Frame:

//Sample 06: Register with the Listener
addWindowListener(this);

And, here is the code which implements all the WindowListener interface functions.

//Sample 07: Implement the Listeners
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {
    this.dispose();
}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}

Note we provided dummy implementation for all the function except the 'windowClosing'. Java AWT calls the 'windowClosing' function when a user clicks the ‘x’ button. We are calling the dispose method in it so that Frame window will get closed and Java AWT will release all associated memories. This ends the Frame window class definition. Now, we will create an instance out of it and display that.

7. Display the AWT Frame

We create a new java file called 'AwtFrame.java' and inside the static main we create the instance of our FrameWin. Note that we did all the work in the constructor itself and once the FrameWin is instantiated, it is ready to display. Hence, we call setVisible method to display the AWT Frame. Below is the code

//Sample 08: Create Frame and Display it
FrameWin fw = new FrameWin("My First Frame");
fw.setVisible(true);

Running the application will show the AWT Frame and its screenshot is given below:

AWT Frame Example
AWT Frame Example | Source

8. Complete Code Listing

8.1 FrameWin.java

import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class FrameWin extends Frame 
implements WindowListener {
    //Sample 01: Constructor
    public FrameWin(String FrameTitle){
        //Sample 02: Set Layout and Title
        super(FrameTitle);
        setLayout(new FlowLayout());
        
        //Sample 03: Create Two Labels
        Label L1 = new Label("Label 1");
        Label L2 = new Label("Label 2");
        
        //Sample 04: Add Label to the 
        //          Frame Window
        add(L1);
        add(L2);
        
        //Sample 05: Set Size of the Frame
        setSize(400, 300);
        setLocation(100,100);
        
        //Sample 06: Register with the Listener
        addWindowListener(this);
        
    }

    //Sample 07: Implement the Listeners
    public void windowOpened(WindowEvent e) {}
    public void windowClosing(WindowEvent e) {
        this.dispose();
    }
    public void windowClosed(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
}

AwtFrame.java

public class AwtFrame {
    public static void main(String[] args) {
        //Sample 08: Create Frame and Display it
        FrameWin fw = new FrameWin("My First Frame");
        fw.setVisible(true);
    }
}

© 2018 sirama

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)