TryGridBagLayout.java Source code

Java tutorial

Introduction

Here is the source code for TryGridBagLayout.java

Source

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.Border;

public class TryGridBagLayout {
    static JFrame aWindow = new JFrame("This is a Gridbag Layout");

    public static void main(String[] args) {
        aWindow.setBounds(30, 30, 300, 300);
        aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints constraints = new GridBagConstraints();
        aWindow.getContentPane().setLayout(gridbag);
        constraints.weightx = constraints.weighty = 10.0;
        constraints.fill = constraints.BOTH;
        addButton(" Press ", constraints, gridbag);
        constraints.gridwidth = constraints.REMAINDER;
        addButton("GO", constraints, gridbag);
        aWindow.setVisible(true);
    }

    static void addButton(String label, GridBagConstraints constraints, GridBagLayout layout) {
        Border edge = BorderFactory.createRaisedBevelBorder();
        JButton button = new JButton(label);
        button.setBorder(edge);
        layout.setConstraints(button, constraints);
        aWindow.getContentPane().add(button);
    }
}