Java Program to Create a Group of Buttons and Arrange them in Container using Flow Layout Manager


This is a Java Program to Create a Group of Right Justified Buttons and Arrange them in Container using Flow Layout Manager

Problem Description

We have to write a program in Java such that it creates a frame with few buttons which are right justified using the Flow Layout Manager.

Expected Input and Output

For creating frame with right justified buttons, we have the following set of input and output.


1. When the frame is created :

On the execution of the program,
it is expected that a frame appears with a few right justified buttons.
Buttons - Button 1, Button 2, Button 3
Problem Solution

1. Create a frame and few buttons.
2. Set the layout of frame as FlowLayout with alignment of components as RIGHT
3. Display the frame.

Program/Source Code

Here is source code of the Java Program to create right justified buttons. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.

  1. /*Java Program to create right justified buttons and 
  2.   arrange in conatiner using Flow Layout Manager*/
  3. import javax.swing.*;
  4. import java.awt.*;
  5. import java.awt.FlowLayout;
  6. class Push_Buttons
  7. {
  8.     //Driver function
  9.     public static void main(String args[])
  10.     {
  11. 	//Create a frame
  12. 	JFrame frame = new JFrame("Buttons");
  13. 	frame.setSize(500,300);
  14. 	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  15. 	//Set the layout of frame as right aligned flow layout
  16. 	frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
  17. 	//Create 3 push buttons
  18. 	JButton[] button = new JButton[3];
  19. 	for(int i=0;i<3;i++)
  20. 	{
  21. 	    button[i]=new JButton("Button "+(i+1));
  22. 	    frame.add(button[i]);
  23. 	}
  24. 	//Display the frame
  25. 	frame.setVisible(true);
  26.     }
  27. }
Program Explanation

1. Set the layout of frame as FlowLayout.
2. Set the alignment of the layout as FlowLayout.RIGHT. This ensures that all the components are right aligned.

Runtime Test Cases

Here’s the run time test case for creating a frame with right justified buttons.

Test case 1 – To view the frame with buttons.

Sanfoundry Global Education & Learning Series – Java Programs.


Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn