You are on page 1of 55

GUI Components Part

2
Chapter 1

How to you lay out


GUI components in
a container?
Use a
layout
manager

Lesson Objectives
At the end of this lesson, you should be able to
Describe the Java GUI API hierarchy
Create user interfaces using frames, panels, and
simple GUI components
Describe the role of layout managers
Use the FlowLayout, GridLayout, and BorderLayout
managers to layout components in a container
Use JPanel as subcontainers
Specify colors and fonts using the Color and Font
classes
Apply common features such as borders, tool tips,
fonts, and colors on Swing components
Use borders to visually group user-interface
components
3

Introduction to Layout Managers


Each container has a layout manager to
arrange the UI components within the
container.
Components are placed in the frame by the
containers layout manager.

There are several different layout


managers that you can choose from to
place components in the desired locations.

4
4

Creating and Setting Layout


Managers

A layout manager is created using a layout

manager class.
Every layout manager class implements
the LayoutManager interface.
You can set the layout manager for a
container using the
setLayout(LayoutManager) method.

5
5

3 Basic Layout Managers

FlowLayout
GridLayout
BorderLayout
Note: By default, the frames layout is
BorderLayout.

6
6

Introduction to FlowLayout
The simplest layout manager.
The components are arranged in the

container from left to right in the order in


which they are added. When one row is filled,
a new row is started.
We can specify the way components are
aligned by using one of the 3 constants:
FlowLayout.RIGHT, FlowLayout.CENTER or
FlowLayout.LEFT
o If you do not specify the alignment, center
alignment is used.

If you resized the frame, the components are7


automatically rearranged to fit in it.

A. Open your Chapter1 NetBeans project


B. Create a new Java Main Class named
ShowFlowLayout to create the following GUI:

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.FlowLayout;
public class ShowFlowLayout extends JFrame {
public ShowFlowLayout() {
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
add(new JLabel("First Name"));
add(new JTextField(8));
add(new JLabel("MI"));
add(new JTextField(1));
add(new JLabel("Last Name"));
add(new JTextField(8));

setTitle("ShowFlowLayout");
setSize(200, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
ShowFlowLayout frame = new ShowFlowLayout();
}
}

10

The FlowLayout Class


java.awt.FlowLayout

The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.

-alignment: int

The alignment of this layout manager (default: CENTER).

-hgap: int

The horizontal gap of this layout manager (default: 5 pixels).

-vgap: int

The vertical gap of this layout manager (default: 5 pixels).

+FlowLayout()

Creates a default FlowLayout manager.

+FlowLayout(alignment: int)

Creates a FlowLayout manager with a specified alignment.

+FlowLayout(alignment: int, hgap:


int, vgap: int)

Creates a FlowLayout manager with a specified alignment,


horizontal gap, and vertical gap.

11

11

P1 Q3

12

Introduction to GridLayout
Arranges components in a grid (matrix)
formation with the number of rows and
columns defined by the constructor.
The components are placed in the grid
from left to right, starting with the first
row, then the second and so on, in the
order in which they are added.

13
13

GridLayout Constructor
The constructor of the GridLayout
manager is as follows:

public GridLayout(int rows, int columns,


int hGap, int vGap)

Constructs a new GridLayout with the

specified number of rows and columns,


along with the specified horizontal and
vertical gaps between components in the
container.

14
14

In your Chapter1 NetBeans project, create a


new Java Main Class named ShowGridLayout
to create the following GUI:

Note
If you resize the frame, the layout of the
components remains unchanged.
All components are given equal size in the container
of GridLayout.

15

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.GridLayout;
public class ShowGridLayout extends JFrame {
public ShowGridLayout() {
setLayout(new GridLayout(3, 2));
add(new JLabel("First Name"));
add(new JTextField(8));
add(new JLabel("MI"));
add(new JTextField(1));
add(new JLabel("Last Name"));
add(new JTextField(8));
16

setTitle("ShowGridLayout");
setSize(250, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
ShowGridLayout frame = new ShowGridLayout();
}
}

17

The GridLayout Class


java.awt.GridLayout

The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.

-rows: int

The number of rows in this layout manager (default: 1).

-columns: int

The number of columns in this layout manager (default: 1).

-hgap: int

The horizontal gap of this layout manager (default: 0).

-vgap: int

The vertical gap of this layout manager (default: 0).

+GridLayout()

Creates a default GridLayout manager.

+GridLayout(rows: int, columns: int) Creates a GridLayout with a specified number of rows and columns.
+GridLayout(rows: int, columns: int, Creates a GridLayout manager with a specified number of rows and
hgap: int, vgap: int)
columns, horizontal gap, and vertical gap.

Note
In FlowLayout and GridLayout, the order in which
the components are added to the container is
important.
It determines the location of the components in the 18
18
container.

P1 Q4

19

Introduction to BorderLayout
Divides the container into five areas: East,
South, West, North, and Center.
Components are added to a BorderLayout by
using the add(Component, index) method
where index is one of the following constants:

BorderLayout.EAST
BorderLayout.SOUTH
BorderLayout.WEST
BorderLayout.NORTH or
BorderLayout.CENTER

The components are laid out according to their


preferred sizes and where they are placed in the
container.

20
20

In your Chapter1 NetBeans project, create a


new Java Main Class named
ShowBorderLayout to create the following GUI:

Note: It is unnecessary to place components to


occupy all the areas - the components in each
area can stretch to fill any empty space.

21

The BorderLayout Class


java.awt.BorderLayout

The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.

-hgap: int

The horizontal gap of this layout manager (default: 0).

-vgap: int

The vertical gap of this layout manager (default: 0).

+BorderLayout()

Creates a default BorderLayout manager.

+BorderLayout(hgap: int, vgap: int) Creates a BorderLayout manager with a specified number of
horizontal gap, and vertical gap.

Note:
The North and South components can stretch
horizontally,
The East and West components can stretch vertically,
The Centre component can stretch both horizontally and
vertically to fill any empty space.

22
22

Additional Methods for Layout


Managers
FlowLayout
setAlignment(value);
setHgap(value);
setVgap(value);

GridLayout

setRows(value);
setColumns(value);
setHgap(value);
setVgap(value);

BorderLayout

setHgap(value);
setVgap(value);

E.g:
FlowLayout flowlayout = new FlowLayout();
flowlayout.setAlignment(FlowLayout.RIGHT);
flowlayout.setHgap(10);
flowlayout.setVgap(20);

23
23

Suppose you want to design an interface as


follows:

It is difficult to achieve the


desired look by placing all
the components in a single

24
24

Use Panels as
Subcontainers

Divide the frame into panels.


Panels act as smaller containers to group UI
components.

You can add buttons to one panel, and then


add the panel to the frame.

25
25

Using Panels as Subcontainers


A frame can contain panels and UI
components. Panels are used to group userinterface components.
Panels can contain other panels.
E.g.

Frame
Panel
User interface
components (UI)

Panel

Panel

Panel

UI

UI

UI

26
26

Steps for Using Panels


1. Create a panel object p1 :
JPanel p1 = new JPanel();
2. Add a GUI component to the panel p1:

p1.add(new JButton(ButtonName));

3. Place the panel into the container as follows:


add(p1);

or, place the panel into another panel:


JPanel p2 = new JPanel();
p2.add(p1);

27
27

In your Chapter1 NetBeans project,


create a new Java Main Class named
TestPanels to create the following GUI:

Note: We can also set the layout manager for a


panel.

By default, JPanel uses FlowLayout.

28

import java.awt.*;
import javax.swing.*;
public class TestPanels extends JFrame {
public TestPanels() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 3));
for (int i = 1; i <= 9; i++) {
buttonPanel.add(new JButton("" + i));
}
buttonPanel.add(new JButton("0"));
buttonPanel.add(new JButton("Start"));
buttonPanel.add(new JButton("Stop"));
29

JPanel controlPanel = new JPanel(new BorderLayout());


controlPanel.add(new JTextField("Time to be displayed here"),
BorderLayout.NORTH);
controlPanel.add(buttonPanel, BorderLayout.CENTER);
add(controlPanel, BorderLayout.EAST);
add(new JButton("Food to be placed here"),
BorderLayout.CENTER);
setTitle("The Front View of a Microwave Oven");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 250);
setVisible(true);
}
public static void main(String[] args) {
TestPanels frame = new TestPanels();
}
}

30

P1
-

Q5
Q6
Q7
Q8
31

The Color Class


You can set colors for GUI components by using
the java.awt.Color class. Colors are made of
red, green, and blue components, each of which
is represented by a byte value that describes its
intensity, ranging from 0 (darkest shade) to 255
(lightest shade). This is known as the RGB
model.
Color c = new Color(r, g, b);
r, g, and b specify a color by its red, green, and
blue components.
Example:
Color c = new Color(228, 100, 255);
32

Standard Colors
13 standard colors (black, blue, cyan,
dark gray, gray, green, light gray,
magenta, orange, pink, red, white,
yellow) are defined as constants in
java.awt.Color:
BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN,
LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED,
WHITE, and YELLOW.

33

Setting Colors
You can use the following methods to set
the components background and
foreground colors:
setBackground(Color c)
setForeground(Color c)

Example:
jbt.setBackground(Color.yellow);
jbt.setForeground(Color.red);

34

In your Chapter1 NetBeans project, create a


new Java Main Class named TestColor.

35

import javax.swing.*;
Import java.awt.BorderLayout;
import java.awt.Color;
public class TestColor extends JFrame {
private JButton jbtEast = new JButton("East");
private JButton jbtWest = new JButton("West");
private JButton jbtNorth = new JButton("North");
private JButton jbtSouth = new JButton("South");
private JButton jbtCenter = new JButton("Center");
public TestColor() {
jbtEast.setBackground(Color.MAGENTA);
jbtEast.setForeground(Color.WHITE);
jbtWest.setBackground(new Color(255, 255, 255));
jbtWest.setForeground(new Color(0, 0, 0));
jbtCenter.setBackground(Color.YELLOW);
jbtCenter.setForeground(new Color(100, 50, 200));
36

add(jbtEast, BorderLayout.EAST);
add(jbtWest, BorderLayout.WEST);
add(jbtNorth, BorderLayout.NORTH);
add(jbtSouth, BorderLayout.SOUTH);
add(jbtCenter, BorderLayout.CENTER);
setTitle("TestColor");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new TestColor();
}
}

37

The Font Class


Font Names

Font Style

Standard font names


that are supported in
all platforms are:
SansSerif, Serif,
Monospaced, Dialog,
or DialogInput.

Font.PLAIN (0),
Font.BOLD (1),
Font.ITALIC (2),
and Font.BOLD +
Font.ITALIC (3)

Font myFont = new Font(name, style, size);

Example:

Font myFont = new Font("SansSerif ", Font.BOLD, 16);


Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12);
JButton jbtOK = new JButton("OK);
jbtOK.setFont(myFont);
38

Finding All Available Font


Names
GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames =
e.getAvailableFontFamilyNames();
for (int i = 0; i < fontnames.length; i++)
System.out.println(fontnames[i]);

39

In your Chapter1 NetBeans project, create a


new Java Main Class named TestFont.

40

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import javax.swing.*;
public class TestFont extends JFrame {
public TestFont() {
GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = e.getAvailableFontFamilyNames();
setLayout(new FlowLayout());
JButton[] buttonArray = new JButton[fontNames.length];
add(new JLabel("Total fonts: " + fontNames.length));

41

for (int i = 0; i < fontNames.length; ++i) {


buttonArray[i] = new JButton((i+1) + ". " + fontNames[i]);
if (i % 2 == 0)
buttonArray[i].setFont(new Font(fontNames[i], Font.BOLD, 16));
else
buttonArray[i].setFont(new Font(fontNames[i], Font.BOLD +
Font.ITALIC, 12));
add(buttonArray[i]);
}
setTitle("TestFont");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1500, 800);
setVisible(true);
}
}
42

Borders
You can set a border on any object of the
JComponent class. Swing has several types of
borders. To create a titled border, use
new TitledBorder(String title)

To create a line border, use


new LineBorder(Color color, int width),

where width specifies the thickness of the line.


For example, the following code displays a titled
border on a panel:
JPanel panel = new JPanel();
panel.setBorder(new TitleBorder(My Panel));

43

Test Swing Common Features


Component Properties

JComponent Properties

font
background
foreground
preferredSize
minimumSize
maximumSize

toolTipText
border

44

In your Chapter1 NetBeans project, create a


new Java Main Class named
TestSwingCommonFeatures.

45

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class TestSwingCommonFeatures extends JFrame {
private JPanel p1 = new JPanel();
private JButton jbtLeft = new JButton("Left");
private JButton jbtCenter = new JButton("Center");
private JButton jbtRight = new JButton("Right");
public TestSwingCommonFeatures() {
jbtLeft.setBackground(Color.WHITE);
jbtCenter.setForeground(Color.GREEN);
jbtRight.setToolTipText("This is the Right button");
46

p1.add(jbtLeft);
p1.add(jbtCenter);
p1.add(jbtRight);
p1.setBorder(new TitledBorder("Three Buttons"));
Font largeFont = new Font("TimesRoman", Font.BOLD, 20);
Border lineBorder = new LineBorder(Color.BLACK, 2);
JPanel p2 = new JPanel(new GridLayout(1, 2));
JLabel jlblRed = new JLabel("Red");
JLabel jlblOrange = new JLabel("Orange");
jlblRed.setForeground(Color.RED);
jlblOrange.setForeground(Color.ORANGE);

47

jlblRed.setFont(largeFont);
jlblOrange.setFont(largeFont);
jlblRed.setBorder(lineBorder);
jlblOrange.setBorder(lineBorder);
p2.add(jlblRed);
p2.add(jlblOrange);
p2.setBorder(new TitledBorder("Two Labels"));
setLayout(new GridLayout(2, 1));
add(p1);
add(p2);
setTitle("TestSwingCommonFeatures");
setSize(300, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
48

P1 Q9

49

Image Icons
Java uses the javax.swing.ImageIcon class to
represent an icon. An icon is a fixed-size picture;
typically it is small and used to decorate
components. Images are normally stored in
image files. You can use new
ImageIcon(filename) to construct an image
icon. For example, the following statement
creates an icon from an image file us.gif in the
image directory under the current class path:
ImageIcon icon = new ImageIcon(
getClass().getResource("images/us.gif"));
50

In your Chapter1 NetBeans project window,


1. Right-click the Source Packages node and
choose New > Java Package
2. In the Package Name text field, replace
newpackage with images.
3. Click Finish.
4. Copy all the image files provided for you in the
image files folder and paste them into the new
package images that you have just created.
5. Create a new Java Main Class named TestImageIcon.

51

import java.awt.*;
import javax.swing.*;
public class TestImageIcon extends JFrame {
private ImageIcon usIcon = new
ImageIcon(getClass().getResource("images/us.gif"));
private ImageIcon myIcon = new
ImageIcon(getClass().getResource("images/my.jpg"));
private ImageIcon frIcon = new
ImageIcon(getClass().getResource("images/fr.gif"));
private ImageIcon ukIcon = new
ImageIcon(getClass().getResource("images/uk.gif"));
public TestImageIcon() {
setLayout(new GridLayout(1, 4, 5, 5));
add(new JLabel(usIcon));
add(new JLabel(myIcon));
add(new JButton(frIcon));
add(new JButton(ukIcon));

52

setTitle("TestImageIcon");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 100);
setVisible(true);
}
public static void main(String[] args) {
new TestImageIcon();
}
}

53

Swing vs. AWT


So why do the GUI component classes have a prefix J? Instead of
JButton, why not name it simply Button? In fact, there is a class
already named Button in the java.awt package.
When Java was introduced, the GUI classes were bundled in a
library known as the Abstract Windows Toolkit (AWT). For every
platform on which Java runs, the AWT components are
automatically mapped to the platform-specific components
through their respective agents, known as peers. AWT is fine for
developing simple graphical user interfaces, but not for
developing comprehensive GUI projects. Besides, AWT is prone to
platform-specific bugs because its peer-based approach relies
heavily on the underlying platform. With the release of Java 2, the
AWT user-interface components were replaced by a more robust,
versatile, and flexible library known as Swing components. Swing
components are painted directly on canvases using Java code,
except for components that are subclasses of java.awt.Window
or java.awt.Panel, which must be drawn using native GUI on a
specific platform. Swing components are less dependent on the
target platform and use less of the native GUI resource. For this
54
reason, Swing components that dont rely on native
GUI are

Review of Lesson Objectives


You should now be able to:
Describe the Java GUI API hierarchy
Create user interfaces using frames, panels, and
simple GUI components
Describe the role of layout managers
Use the FlowLayout, GridLayout, and BorderLayout
managers to layout components in a container
Use JPanel as subcontainers
Specify colors and fonts using the Color and Font
classes
Apply common features such as borders, tool tips,
fonts, and colors on Swing components
Use borders to visually group user-interface
components

You might also like