This tutorial is about the BoxLayout as Layout Manager in Java. A
BoxLayout as a layout come from the Box class where it provides each component's x and y alignment properties with its sizes.
So, now let's start this tutorial!
1. Open JCreator or NetBeans and make a java program with a file name of
boxLayout.java.
2. Import the javax.swing.* package library that is used to access the BoxLayout, JButton, and JFrame class.
import javax.swing.*; // used to access the BoxLayout, JButton, and JFrame class
3. Initialize your variable in your Main, variable
frame for JFrame, and 3 buttons namely
b1,
b2, and
b3 as JButton.
Now, we will initialize a BoxLayout class and will name it as variable
boxLayout. The
BoxLayout automatically arranges your components in row or column position, or the x and y axis position alignment properties together with its size. The BoxLayout has one constructor namely the
Target Components and the
Axis Alignment Property. The
Target argument is where the components are to be placed and the
Axis argument specifies what alignment that the components must have. There are four axis constants:
BoxLayout.X_AXIS, BoxLayout.Y_AXIS, BoxLayout.LINE_AXIS, and BoxLayout.PAGE_AXIS. Now to declare a BoxLayout, have the code below:
4. Then add the buttons into the frame using the
add method.
frame.getContentPane().add(b1);
frame.getContentPane().add(b2);
frame.getContentPane().add(b3);
To have a BoxLayout as the layout manager, we will use the
setLayout method of the frame.
frame.getContentPane().setLayout(boxLayout);
5. Lastly, pack the frame, set visibility, and the close operation of the frame. Have this code below:
frame.pack();
frame.
setDefaultCloseOperation(JFrame.
EXIT_ON_CLOSE); frame.setVisible(true);
Output:
Here's the full code of this tutorial:
import javax.swing.*; // used to access the BoxLayout, JButton, and JFrame class
import javax.swing.JButton;
import javax.swing.JFrame;
public class boxLayout {
public static void main
(String[] args
) {
frame.getContentPane().setLayout(boxLayout);
frame.getContentPane().add(b1);
frame.getContentPane().add(b2);
frame.getContentPane().add(b3);
frame.pack();
frame.
setDefaultCloseOperation(JFrame.
EXIT_ON_CLOSE); frame.setVisible(true);
}
}
For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below.
Best Regards,
Engr. Lyndon Bermoy
IT Instructor/System Developer/Android Developer/Freelance Programmer
Mobile: 09488225971
Landline: 826-9296
E-mail:
[email protected]
Add and Follow me on Facebook:
https://www.facebook.com/donzzsky
Visit and like my page on Facebook at:
https://www.facebook.com/BermzISware