Java Tutorial
In java programming, we can also use grid 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 Layout is used to put the components with an arrangement of rows and columns in the JFrame.
setLayout(new GridLayout(int rows, int columns));
This java code uses 2 rows and 4 columns in grid layout to arrange the 8 button components.
// importing swing package for JFrame, Jbutton controls import javax.swing.*; // importing to use Container class import java.awt.*; public class GridLayoutTest extends JFrame { public GridLayoutTest(){ // Setting Title to the JFrame GUI setTitle("Grid Layout Test Java Code"); // Setting grid layout to JFrame GUI setLayout(new GridLayout(2,4)); // Adding buttons using Grid Layout add(new JButton("Button1")); add(new JButton("Button2")); add(new JButton("Button3")); add(new JButton("Button4")); add(new JButton("Button5")); add(new JButton("Button6")); add(new JButton("Button7")); add(new JButton("Button8")); } public static void main(String[] args){ // Create JFrame for GUI frame and title as 'Add Button in JFrame Java Code' GridLayoutTest frame = new GridLayoutTest(); frame.setSize(500,200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }Output:
Once executing this java program, Frame with grid layout buttons will be popped up as above and closes if we click close button in the frame title.
// Setting grid layout to JFrame GUI setLayout(new GridLayout(2,4)); // Adding buttons using Grid Layout add(new JButton("Button1")); add(new JButton("Button2")); add(new JButton("Button3")); add(new JButton("Button4")); add(new JButton("Button5")); add(new JButton("Button6")); add(new JButton("Button7"));Output:
setLayout(new GridLayout(2,4)); // Adding buttons using Grid Layout add(new JButton("Button1")); add(new JButton("Button2")); add(new JButton("Button3")); add(new JButton("Button4")); add(new JButton("Button5")); add(new JButton("Button6"));Output:
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page