Java GUI layout
Creating a graphical user interface and placing components on it is great, but how are you going to layout those components? For this task layout managers are used.
This tutorial focuses on:
- Layout manager classes
- Setting a layout
- The FlowLayout class
- The GridLayout class
Layout manager classes
Layout manager classes are located in the java.awt package just like the classes used for displaying graphical components. So no need to to import any extra packages when you're using layout managers.
Setting a layout
You can set a frame to use a layout using the setLayout() method of the Frame class.
Example:
Frame AFrame = new Frame("Frame with components");
AFrame.setSize(450, 300);
//set the layout of the frame to FlowLayout
AFrame.setLayout(new FlowLayout());
AFrame.setVisible(true);
The FlowLayout class
The FlowLayout class is used to arrange components from left to right. If there is no more room, the next component will be wrapped onto a new line.
FlowLayout class constructors:
-
FlowLayout() - Creates a FlowLayout.
-
FlowLayout(int alignment) - Creates a FlowLayout with the specified alignment. Possible values include
FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT, FlowLayout.LEADING, FlowLayout.TRAILING.
A frame using a flow layout:import java.awt.*;
class FrameWithFlowLayout{
public static void main(String[] args){
Frame AFrame = new Frame("Frame with components");
Label lblOne = new Label("This is a label");
Button btn1 = new Button("This is a button");
TextField tf1 = new TextField();
tf1.setText("This is a textbox");
AFrame.add(lblOne);
AFrame.add(btn1);
AFrame.add(tf1);
AFrame.setSize(450, 300);
//set the layout of the frame to FlowLayout
//and align the components to the center
AFrame.setLayout(new FlowLayout(FlowLayout.CENTER));
AFrame.setVisible(true);
}
}
What it will look like:
The GridLayout class
The GridLayout class is used to arrange components in a grid of equally sized rectangular cells.
GridLayout class constructors:
-
GridLayout() - Creates a GridLayout which has one row by default.
-
GridLayout(int rows, int columns) - Creates a GridLayout with the specified number of rows and columns.
A frame using a grid layout:import java.awt.*;
class FrameWithGridLayout{
public static void main(String[] args){
Frame AFrame = new Frame("Frame with components");
Label lblOne = new Label("This is a label");
Button btn1 = new Button("This is a button");
TextField tf1 = new TextField();
TextArea ta1 = new TextArea(12, 40);
tf1.setText("This is a textbox");
ta1.append("Number of columns in this textarea: " + ta1.getColumns());
AFrame.add(lblOne);
AFrame.add(btn1);
AFrame.add(tf1);
AFrame.add(ta1);
AFrame.setSize(480, 300);
//set the layout of the frame to GridLayout
//specify the layout to have 2 rows and 2 columns
AFrame.setLayout(new GridLayout(2, 2));
AFrame.setVisible(true);
}
}
What it will look like: