Professional Documents
Culture Documents
Swing, Layout Managers
Swing, Layout Managers
Swing
Java Swing is used to create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Hierarchy of Java Swing classes:
Commonly used Methods of Component class
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.
We can write the code of swing inside the main(), constructor or any other method.
Swing by inheritance
We can also inherit the JFrame class, so there is no need to create the instance of JFrame class
explicitly.
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }
16. }
Java JButton
The JButton class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed. It inherits AbstractButton class.
1. import java.awt.event.*;
2. import javax.swing.*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5. JFrame f=new JFrame("Button Example");
6. final JTextField tf=new JTextField();
7. tf.setBounds(50,50, 150,20);
8. JButton b=new JButton("Click Here");
9. b.setBounds(50,100,95,30);
10. b.addActionListener(new ActionListener(){
11. public void actionPerformed(ActionEvent e){
12. tf.setText("Welcome to Javatpoint.");
13. }
14. });
15. f.add(b);f.add(tf);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. }
20. }
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an
interface that is implemented by all the classes of layout managers. There are following classes that
represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the
default layout of applet or panel.
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed
in each rectangle.
Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns
but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14. JButton b6=new JButton("6");
15. JButton b7=new JButton("7");
16. JButton b8=new JButton("8");
17. JButton b9=new JButton("9");
18.
19. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
20. f.add(b6);f.add(b7);f.add(b8);f.add(b9);
21.
22. f.setLayout(new GridLayout(3,3));
23. //setting grid layout of 3 rows and 3 columns
24.
25. f.setSize(300,300);
26. f.setVisible(true);
27. }
28. public static void main(String[] args) {
29. new MyGridLayout();
30. }
31. }
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along their
baseline.
The components may not be of same size. Each GridBagLayout object maintains a dynamic,
rectangular grid of cells. Each component occupies one or more cells known as its display area.
Each component associates an instance of GridBagConstraints. With the help of constraints object
we arrange component's display area on the grid. The GridBagLayout manages each component's
minimum and preferred sizes in order to determine component's size.
Fields
Modifier and Type Field Description
It is used to hold the overrides to the
double[] columnWeights
column weights.
It is used to hold the overrides to the
int[] columnWidths
column minimum width.
protected It is used to maintains the association
Hashtable<Component,GridBagC comptable between a component and its gridbag
onstraints> constraints.
It is used to hold a gridbag constraints
protected GridBagConstraints defaultConstraints
instance containing the default values.
It is used to hold the layout information for
protected GridBagLayoutInfo layoutInfo
the gridbag.
No longer in use just for backward
protected static int MAXGRIDSIZE
compatibility
It is smallest grid that can be laid out by the
protected static int MINSIZE
grid bag layout.
It is preferred grid size that can be laid out
protected static int PREFERREDSIZE
by the grid bag layout.
It is used to hold the overrides to the row
int[] rowHeights
minimum heights.
It is used to hold the overrides to the row
double[] rowWeights
weights.
Useful Methods
Modifier and Type Method Description
It adds specified component to the
addLayoutComponent(Componen
void layout, using the specified constraints
t comp, Object constraints)
object.
void addLayoutComponent(String It has no effect, since this layout
name, Component comp) manager does not use a per-component
string.
It adjusts the x, y, width, and height
adjustForGravity(GridBagConstra
protected void fields to the correct values depending on
ints constraints, Rectangle r)
the constraint geometry and pads.
AdjustForGravity(GridBagConstr This method is for backwards
protected void
aints constraints, Rectangle r) compatibility only
protected void arrangeGrid(Container parent) Lays out the grid.
This method is obsolete and supplied for
protected void ArrangeGrid(Container parent)
backwards compatibility
It is for getting the constraints for the
GridBagConstraints getConstraints(Component comp)
specified component.
getLayoutAlignmentX(Container
float It returns the alignment along the x axis.
parent)
getLayoutAlignmentY(Container
float It returns the alignment along the y axis.
parent)
It determines column widths and row
int[][] getLayoutDimensions()
heights for the layout grid.
protected getLayoutInfo(Container parent, This method is obsolete and supplied for
GridBagLayoutInfo int sizeflag) backwards compatibility.
protected GetLayoutInfo(Container parent, This method is obsolete and supplied for
GridBagLayoutInfo int sizeflag) backwards compatibility.
It determines the origin of the layout
Point getLayoutOrigin() area, in the graphics coordinate space of
the target container.
It determines the weights of the layout
double[][] getLayoutWeights()
grid's columns and rows.
It figures out the minimum size of the
getMinSize(Container parent,
protected Dimension master based on the information from
GridBagLayoutInfo info)
getLayoutInfo.
GetMinSize(Container parent, This method is obsolete and supplied for
protected Dimension
GridBagLayoutInfo info) backwards compatibility only
1. import java.awt.GridBagConstraints;
2. import java.awt.GridBagLayout;
3.
4. import javax.swing.*;
5. public class GridBagLayoutExample extends JFrame{
6. public static void main(String[] args) {
7. GridBagLayoutExample a = new GridBagLayoutExample();
8. }
9. public GridBagLayoutExample() {
10. GridBagLayoutgrid = new GridBagLayout();
11. GridBagConstraints gbc = new GridBagConstraints();
12. setLayout(grid);
13. setTitle("GridBag Layout Example");
14. GridBagLayout layout = new GridBagLayout();
15. this.setLayout(layout);
16. gbc.fill = GridBagConstraints.HORIZONTAL;
17. gbc.gridx = 0;
18. gbc.gridy = 0;
19. this.add(new Button("Button One"), gbc);
20. gbc.gridx = 1;
21. gbc.gridy = 0;
22. this.add(new Button("Button two"), gbc);
23. gbc.fill = GridBagConstraints.HORIZONTAL;
24. gbc.ipady = 20;
25. gbc.gridx = 0;
26. gbc.gridy = 1;
27. this.add(new Button("Button Three"), gbc);
28. gbc.gridx = 1;
29. gbc.gridy = 1;
30. this.add(new Button("Button Four"), gbc);
31. gbc.gridx = 0;
32. gbc.gridy = 2;
33. gbc.fill = GridBagConstraints.HORIZONTAL;
34. gbc.gridwidth = 2;
35. this.add(new Button("Button Five"), gbc);
36. setSize(300, 300);
37. setPreferredSize(getSize());
38. setVisible(true);
39. setDefaultCloseOperation(EXIT_ON_CLOSE);
40.
41. }
42.
43. }
Java CardLayout
The CardLayout class manages the components in such a manner that only one component is visible
at a time. It treats each component as a card that is why it is known as CardLayout.
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e) {
card.next(c);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}