Friday, 14 July 2017

BoxLayout in java ~ java help

Java BoxLayout

The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose, BoxLayout provides four constants. They are as follows:

Note: BoxLayout class is found in javax.swing package.

Fields of BoxLayout class

  1. public static final int X_AXIS
  2. public static final int Y_AXIS
  3. public static final int LINE_AXIS
  4. public static final int PAGE_AXIS

Constructor of BoxLayout class

  1. BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given axis.

Example of BoxLayout class with Y-AXIS:

BoxLayout class
  1. import java.awt.*;  
  2. import javax.swing.*;  
  3.   
  4. public class BoxLayoutExample1 extends Frame {  
  5.  Button buttons[];  
  6.   
  7.  public BoxLayoutExample1 () {  
  8.    buttons = new Button [5];  
  9.     
  10.    for (int i = 0;i<5;i++) {  
  11.       buttons[i] = new Button ("Button " + (i + 1));  
  12.       add (buttons[i]);  
  13.     }  
  14.   
  15. setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));  
  16. setSize(400,400);  
  17. setVisible(true);  
  18. }  
  19.   
  20. public static void main(String args[]){  
  21. BoxLayoutExample1 b=new BoxLayoutExample1();  
  22. }  
  23. }  


Example of BoxLayout class with X-AXIS

BoxLayout class example
  1. import java.awt.*;  
  2. import javax.swing.*;  
  3.   
  4. public class BoxLayoutExample2 extends Frame {  
  5.  Button buttons[];  
  6.   
  7.  public BoxLayoutExample2() {  
  8.    buttons = new Button [5];  
  9.     
  10.    for (int i = 0;i<5;i++) {  
  11.       buttons[i] = new Button ("Button " + (i + 1));  
  12.       add (buttons[i]);  
  13.     }  
  14.   
  15. setLayout (new BoxLayout(this, BoxLayout.X_AXIS));  
  16. setSize(400,400);  
  17. setVisible(true);  
  18. }  
  19.   
  20. public static void main(String args[]){  
  21. BoxLayoutExample2 b=new BoxLayoutExample2();  
  22. }  
  23. }  

No comments:

Post a Comment