Rabu, 13 Agustus 2025

JAVA - Grid Bag Layout

 




/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package tgridbaglayout;

import javax.swing.*;

import java.awt.*;


public class TGridBagLayout extends JApplet {

    Container container = null;


    public void init() {

        // 1. Get a handle on the applet's content pane.

        container = this.getContentPane();


        // 2. Set the container to the grid bag layout and

        // define a constraint object.

        GridBagLayout gridbag = new GridBagLayout();

        container.setLayout(gridbag);

        GridBagConstraints c = new GridBagConstraints();


        // 3. Common settings for constraint object instant variables.

        c.fill = GridBagConstraints.BOTH;


        // 4. Settings for button B1.

        c.insets = new Insets(5,5,5,5);

        c.gridx = 0; c.gridy = 0;

        c.gridwidth = 2; c.gridheight = 2;

        c.weightx = 1.0; c.weighty = 1.0;

        makeButton("B1", gridbag, c);


        // 5. Settings for button B2.

        c.insets = new Insets(0,0,0,0);

        c.gridx = 2; c.gridy = 0;

        c.gridwidth = 1; c.gridheight = 3;

        makeButton("B2", gridbag, c);


        // 6. Settings for button B3.

        c.gridx = 0; c.gridy = 2;

        c.gridwidth = 1; c.gridheight = 1;

        c.weightx = 1.0; c.weighty=0.5;

        makeButton("B3", gridbag, c);


        // 7. Settings for button B4.

        c.gridx = 1; c.gridy = 2;

        makeButton("B4", gridbag, c);

    }


    // 8. Define the function to create and add a button

    // according to the constraints.

    public void makeButton(String name,

                           GridBagLayout gridbag,

                           GridBagConstraints c) {

        JButton button = new JButton(name);

        gridbag.setConstraints(button, c);

        container.add(button);

    }

}


Tidak ada komentar: