Java AWT Creating Piano Buttons with Grid Layout

Java AWT Creating Piano Buttons with Grid Layout:

This code is continuation of this tutorial Java AWT Changing Button Size in Flow Layout.  Just delete line 24 in the previous code and change line 45 to GridLayout in that code.


GridLayout Piano Type Buttons:

creating piano type button with awt grid layout
creating piano type button with awt grid layout

 

Code AWT GridLayout Piano Type Buttons:

import java.awt.*;
import java.awt.event.*;

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

    private static final int button_count = 10;

    // Declare a Frame type variable
    Frame frame;

    // Create an array of Button type Objects
    Button [] button = new Button[button_count];

    public SimpleAwtGui() {
        // Create Frame Object and pass in the Frame Name / title
        frame = new Frame("AWT GUI EXAMPLE");

        // Use for loop to instantiate every button object
        for(int i = 0; i < button_count; ++i){
            button[i] = new Button( "" + i );
        }

    }

    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();

    }

    // 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 GridLayout());

        // Add all of the buttons to the layout
        for(int i = 0; i < button_count; ++i) {
            frame.add(button[i]);
        }

        // Register window listener event to the frame without implementing WindowListener
        frame.addWindowListener(
                new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                }
        );

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

One thought on “Java AWT Creating Piano Buttons with Grid Layout

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