BoxLayout in java

BoxLayout

  • It layout manager allows multiple component to be laid out either vertically or horizontally.
  • The component will not wrap.
Example

import java.awt.*;
import javax.swing.*;

import javax.swing.*;
public class test extends JFrame
{
Container c;
test()
{
c= getContentPane();
c.setLayout(new FlowLayout());
MyPanel1 mp1 = new MyPanel1();
c.add(mp1);
MyPanel2 mp2 = new MyPanel2();
c.add(mp2);
}
public static void main(String[] args)
{
test t = new test();
t.setSize(400,400);
t.setTitle(“Box Layout”);
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class MyPanel1 extends JPanel
{
MyPanel1()
{
BoxLayout obj1 = new BoxLayout(this, BoxLayout.X_AXIS);
setLayout(obj1);
JButton b1=new JButton(“White”);
JButton b2=new JButton(“Orange”);
JButton b3=new JButton(“Green”);
JButton b4=new JButton(“Red”);
JButton b5=new JButton(“Blue”);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
}
}
class MyPanel2 extends JPanel
{
MyPanel2()
{
BoxLayout obj2 = new BoxLayout(this, BoxLayout.Y_AXIS);
setLayout(obj2);
JButton b1=new JButton(“White”);
JButton b2=new JButton(“Orange”);
JButton b3=new JButton(“Green”);
JButton b4=new JButton(“Red”);
JButton b5=new JButton(“Blue”);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
}
}
}
Output:

Untitled

Leave a Reply

Your email address will not be published. Required fields are marked *