Java Swing GUI

BoxLayout – Java Swing – Example

In this tutorial, we are going to see an example of BoxLayout in Java Swing. BoxLayout is used to organize the components vertically or horizontally. For this purpose, BoxLayout provides four constants.

Fields of BoxLayout class:

  • public static final int X_AXIS
  • public static final int Y_AXIS
  • public static final int LINE_AXIS
  • public static final int PAGE_AXIS
 

Example 1: Arranging components horizontally
import java.awt.*;
import javax.swing.*;

public class BoxExemple extends Frame 
{
	public BoxExemple() 
	{
		Button btn1 = new Button("A");
		Button btn2 = new Button("B");
		Button btn3 = new Button("C");
		Button btn4 = new Button("D");
		
		add(btn1);
		add(btn2);
		add(btn3);
		add(btn4);
		
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		setSize(300,300);
		setVisible(true);
	}

	public static void main(String args[]){
		BoxExemple box = new BoxExemple();
	}
}

Output:


 

Example 2: Arranging components vertically
import java.awt.*;
import javax.swing.*;

public class BoxExemple extends Frame 
{
	public BoxExemple() 
	{
		Button btn1 = new Button("A");
		Button btn2 = new Button("B");
		Button btn3 = new Button("C");
		Button btn4 = new Button("D");
		
		add(btn1);
		add(btn2);
		add(btn3);
		add(btn4);
		
		setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
		setSize(300,300);
		setVisible(true);
	}

	public static void main(String args[]){
		BoxExemple box = new BoxExemple();
	}
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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