Java Tutorial
In java programming, we can also use grid bag layout in JFrame to create a Graphical user interface (GUI) using JFrame class.
In Java JFrame, need to set the layout to add the components.
Grid Bag Layout is used to put the components to specified location in the JFrame.
GridBagConstraints object has gridx and gridy properties to specify the position of components.
setLayout(new GridBagLayout());
This java code uses grid bag layout to arrange the button components.
// importing swing package for JFrame, JButton controls import javax.swing.*; // importing to use Container class import java.awt.*; public class GridBagLayoutTest extends JFrame { public GridBagLayoutTest(){ // Setting Title to the JFrame GUI setTitle("Grid Bag Layout Test Java Code"); // Setting grid bag layout to JFrame GUI setLayout(new GridBagLayout()); // Setting position for the component GridBagConstraints place = new GridBagConstraints(); place.gridx = 5; place.gridy = 0; // Adding buttons using Grid Bag Layout add(new JButton("Button1"), place); //Setting position for the button2 component place.gridx = 0; place.gridy = 5; add(new JButton("Button2"), place); //Setting position for the button2 component place.gridx = 2; place.gridy = 4; add(new JButton("Button3"), place); } public static void main(String[] args){ // Create JFrame for GUI frame and title as 'Add Button in JFrame Java Code' GridBagLayoutTest frame = new GridBagLayoutTest(); frame.setSize(500,200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }Output:
Once executing this java program, Frame with grid bag layout buttons will be popped up as above and closes if we click close button in the frame title.
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page