Java Tutorial
In java programming, we can also use box 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.
Box Layout is used to put the components in X-Axis or Y-Axis direction in the JFrame.
setLayout(new BoxLayout(Container panel, int axis));
Container panel uses the Box layout and axis sets the components arranged in x axis direction or in y axis direction.
This java code uses box 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 BoxLayoutTest extends JFrame { public BoxLayoutTest(){ // Setting Title to the JFrame GUI setTitle("Grid Bag Layout Test Java Code"); // Creating content panel to add the panels. Container container = getContentPane(); JPanel panel = new JPanel(); // Setting box layout to JFrame GUI panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // Adding buttons using Box Layout panel.add(new JButton("Button1")); panel.add(new JButton("Button2")); panel.add(new JButton("Button3")); panel.add(new JButton("Button4")); panel.add(new JButton("Button5")); // adds panel into Container container.add(panel); //Adjust the size of all components. this.pack(); } public static void main(String[] args){ // Create JFrame for GUI frame and title as 'Add Button in JFrame Java Code' BoxLayoutTest frame = new BoxLayoutTest(); frame.setSize(500,200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }Output:
Box layout Y Axis
Box layout X Axis
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
Once executing this java program, Frame with box layout buttons arranged either X-Axis or Y-Axis direction 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