AWT de Java | Clase GridBagLayout

La clase GridBagLayout es un administrador de diseño flexible. Se utiliza para alinear los componentes horizontalmente, verticalmente oa lo largo de su línea de base. No requiere los componentes del mismo tamaño. Cada objeto GridBagLayout administra una cuadrícula rectangular de celdas, dinámica con cada componente ocupando una o más celdas, denominada área de visualización. Los componentes GridBagLayout están asociados con la instancia de GridBagConstraints. Estas restricciones se utilizan para definir el área de visualización del componente y sus posiciones. Además de su objeto de restricciones, GridBagLayout también considera los tamaños mínimo y preferido de cada componente para determinar el tamaño de un componente. Los componentes GridBagLayout también se organizan en la cuadrícula rectangular, pero pueden tener diferentes tamaños y pueden ocupar varias filas o columnas.

Constructor: 

  • GridBagLayout(): se utiliza para crear un administrador de diseño de bolsas de cuadrícula.

Métodos comúnmente utilizados:  

  • removeLayoutComponent(Component cmp): elimina el componente especificado de este diseño.
  • getLayoutAlignmentY(Container p): Devuelve la alineación a lo largo del eje y.
  • addLayoutComponent(Component cmp, Object cons): agrega el componente especificado con el nombre especificado al diseño.
  • toString(): Devuelve una representación de string de los valores de este diseño de bolsa de cuadrícula.
  • getLayoutAlignmentX(Container p): Devuelve la alineación a lo largo del eje x.
  • getConstraints(Component cmp): Obtiene las restricciones para el componente especificado.
  • maximumLayoutSize(Container tar): devuelve las dimensiones máximas para este diseño dados los componentes en el contenedor de destino especificado.
  • minimalLayoutSize(Container par): determina el tamaño mínimo del contenedor principal utilizando este diseño de bolsa de cuadrícula.

Los siguientes programas ilustran la clase GridBagLayout:  

  • Programa 1: el programa a continuación organiza los diversos componentes de fila y columna en un JFrame , cuya clase de instancia se denomina » Gridbagdemo «. Creamos 4 componentes JButton llamados » java «, » layout «, » manager «, » demo » y luego los agregamos al JFrame mediante el método add() . Establecemos el tamaño y la visibilidad del marco mediante el método setSize() y setVisible() . El diseño se establece mediante el método setLayout() .

Java

// Java program to demonstrate GridBagLayout class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.*;
 
// class extends JFrame
public class GridbagDemo extends JFrame {
 
    GridbagDemo()
    {
 
        // Function to set title of JFrame.
        setTitle("GridBagLayoutDemo");
 
        // Creating Object of Jpanel class
        JPanel p = new JPanel();
 
        // set the layout
        p.setLayout(new GridBagLayout());
 
        // creates a constraints object
        GridBagConstraints c = new GridBagConstraints();
 
        // insets for all components
        c.insets = new Insets(2, 2, 2, 2);
 
        // column 0
        c.gridx = 0;
 
        // row 0
        c.gridy = 0;
 
        // increases components width by 10 pixels
        c.ipadx = 15;
 
        // increases components height by 50 pixels
        c.ipady = 50;
 
        // constraints passed in
        p.add(new JButton("Java Swing"), c);
 
        // column 1
        c.gridx = 1;
 
        // increases components width by 70 pixels
        c.ipadx = 90;
 
        // increases components height by 40 pixels
        c.ipady = 40;
 
        // constraints passed in
        p.add(new JButton("Layout"), c);
 
        // column 0
        c.gridx = 0;
 
        // row 2
        c.gridy = 1;
 
        // increases components width by 20 pixels
        c.ipadx = 20;
 
        // increases components height by 20 pixels
        c.ipady = 20;
 
        // constraints passed in
        p.add(new JButton("Manager"), c);
 
        // increases components width by 10 pixels
        c.ipadx = 10;
 
        // column 1
        c.gridx = 1;
 
        // constraints passed in
        p.add(new JButton("Demo"), c);
 
        // Creating Object of "wndcloser"
        // class of windowlistener
        WindowListener wndCloser = new WindowAdapter() {
 
            public void windowClosing(WindowEvent e)
            {
 
                // exit the system
                System.exit(0);
            }
        };
 
        // add the actionwindowlistener
        addWindowListener(wndCloser);
 
        // add the content
        getContentPane().add(p);
 
        // Function to set size of JFrame.
        setSize(600, 400);
 
        // Function to set visibility of JFrame.
        setVisible(true);
    }
 
    // Main Method
    public static void main(String[] args)
    {
 
        // calling the constructor
        new GridbagDemo();
    }
}

Producción:

  • Programa 2: el programa a continuación organiza los diversos componentes de fila y columna en un JFrame , cuya clase de instancia se denomina » Gridbagdemo «. Creamos 5 componentes JButton y luego los agregamos al JFrame mediante el método add() . Establecemos el título, el tamaño y la visibilidad del marco mediante el método setTitle, setSize() y setVisible() . El diseño se establece mediante el método setLayout() .

Java

// Java program to demonstrate GridBagLayout class.
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
  
// Constructor of GridBagLayout class.
public class GridBagLayoutDemo {
  
    final static boolean shouldFill = true;
    final static boolean shouldWeightX = true;
    final static boolean RIGHT_TO_LEFT = false;
  
public static void addComponentsToPane(Container pane)
{
 
    // if condition
    if (RIGHT_TO_LEFT) {
 
        pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    }
 
    // Declaration of objects of JButton class
    JButton button;
 
    // set the layout
    pane.setLayout(new GridBagLayout());
 
    // creates a constraints object
    GridBagConstraints c = new GridBagConstraints();
 
    // if condition
    if (shouldFill) {
 
        // natural height, maximum width
        c.fill = GridBagConstraints.HORIZONTAL;
    }
 
    // Initialization of object
    // "button" of JButton class.
    button = new JButton("Button 1");
 
    // if condition
    if (shouldWeightX) {
        c.weightx = 0.5;
    }
 
    // column 0
    c.gridx = 0;
 
    // row 0
    c.gridy = 0;
 
    // Adding JButton "button" on JFrame.
    pane.add(button, c);
 
    // Initialization of object
    // "button" of JButton class.
    button = new JButton("Button 2");
 
    // column 1
    c.gridx = 1;
 
    // row 0
    c.gridy = 0;
 
    // Adding JButton "button" on JFrame.
    pane.add(button, c);
 
    // Initialization of object
    // "button" of JButton class.
    button = new JButton("Button 3");
 
    // column 1
    c.gridx = 2;
 
    // row 0
    c.gridy = 0;
 
    // Adding JButton "button" on JFrame.
    pane.add(button, c);
 
    // Initialization of object
    // "button" of JButton class.
    button = new JButton("Long-Named Button 4");
 
    // increases components height by 40 pixels
    c.ipady = 40;
 
    // column width 0
    c.weightx = 0.0;
 
    // row width 3
    c.gridwidth = 3;
 
    // column 1
    c.gridx = 0;
 
    // row 1
    c.gridy = 1;
 
    // Adding JButton "button" on JFrame.
    pane.add(button, c);
 
    // Initialization of object
    // "button" of JButton class.
    button = new JButton("Button 5");
 
    // increases components height by 0 pixels
    c.ipady = 0;
 
    // request any extra vertical space
    c.weighty = 1.0;
 
    // bottom of space
    c.anchor = GridBagConstraints.PAGE_END;
 
    // top padding
    c.insets = new Insets(10, 0, 0, 0);
 
    // column 2
    c.gridx = 1;
 
    // 2 columns wide
    c.gridwidth = 2;
 
    // row 3
    c.gridy = 2;
 
    // Adding JButton "button" on JFrame.
    pane.add(button, c);
}
 
// Create the GUI and show it.  For thread safety,
// this method should be invoked from the
// event-dispatching thread.
private static void createAndShowGUI()
{
 
    // to set a Jframe default
    JFrame.setDefaultLookAndFeelDecorated(true);
 
    // Create and set up the window.
    JFrame frame = new JFrame("GridBagLayoutDemo");
 
    // Function to close the operation of JFrame.
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
    // adding the content pane.
    addComponentsToPane(frame.getContentPane());
 
    // Display the window.
    frame.pack();
 
    // Function to set visible status of JFrame.
    frame.setVisible(true);
}
 
    // Main Method
    public static void main(String[] args)
    {
  
        // Schedule a job for the event-dispatching thread:
        // creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
  
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}

Producción:

Nota: Es posible que los programas anteriores no se ejecuten en un IDE en línea. Utilice un compilador fuera de línea.
Referencia: https://docs.oracle.com/javase/7/docs/api/java/awt/GridBagLayout.html
 

Publicación traducida automáticamente

Artículo escrito por Shivi_Aggarwal y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *