Adding a Button to the AWT Window

Adding a Button to the AWT Window:

This tutorial is continuation of tutorial creating a java AWT window. This code is extension of previous code. Here I’ve only added three separate pieces of code to the previous one.

Diff with previous code from creating a java AWT:

awt gui window add button component
awt gui window add button component

AWT Window with Button:

awt gui add button sample window
awt gui add button sample window

 

Code Add Button to AWT GUI Window:

import java.awt.*;

/**
 * Created by asif on 8/13/2015.
 */
public class SimpleAwtGui {

    // Declare a Frame type variable
    Frame frame;
    Button button;

    public SimpleAwtGui(){
         // Create Frame Object and pass in the Frame Name / title
        frame = new Frame("AWT GUI EXAMPLE");
        button = new Button("I am here Click Me");
    }

    /*
     * Not necessary but good practice all codes inside this can be written inside main
     */
    public void showFrame(){
        // set the size of the window
        frame.setSize(400, 400);

        // set the layout for the window
        frame.setLayout(new FlowLayout());

        // Add the button component to frame otherwise button won't show
        frame.add(button);

        // set the frame visible otherwise nothing will be shown
        frame.setVisible(true);
    }

    public static void main(String [] args){

        // Create an instance of SimpleAwtGui
        SimpleAwtGui window = new SimpleAwtGui();

        // call the showFrame() function to display the window
        window.showFrame();

    }
}
Advertisements

2 thoughts on “Adding a Button to the AWT Window

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s