0% found this document useful (0 votes)
2 views

Chapter 1 Intro to GUI - Part 1_ 2

Chapter 1 introduces GUI components and their usage in Java, focusing on creating applications with dialog boxes and extending the JFrame class. It covers various types of dialog boxes, including message, input, and confirmation dialogs, as well as the importance of good UI design and the Java GUI API hierarchy. The chapter also discusses layout managers and provides examples of creating GUI components such as buttons, labels, and text fields.

Uploaded by

Sheueyin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter 1 Intro to GUI - Part 1_ 2

Chapter 1 introduces GUI components and their usage in Java, focusing on creating applications with dialog boxes and extending the JFrame class. It covers various types of dialog boxes, including message, input, and confirmation dialogs, as well as the importance of good UI design and the Java GUI API hierarchy. The chapter also discusses layout managers and provides examples of creating GUI components such as buttons, labels, and text fields.

Uploaded by

Sheueyin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

Chapter 1

GUI Components I – Part 1


Lesson Objectives
At the end of this lesson, you should be able to
• Create a simple application using dialog boxes.
• Describe what are components and containers in a
graphical user interface.
• Create a GUI application class by extending the
JFrame class.

2
Introduction
• A graphical user interface (GUI) makes a
system user-friendly and easy to use.

3
Dialog Boxes
• Also known as dialogs.
• Windows in which programs display important
messages to the user or obtain information
from the user.
• Java’s javax.swing.JOptionPane class
provides pre-built dialog boxes for input and
output.

4
A. Create a new NetBeans project named Chapter1
Uncheck the Create Main Class checkbox.
B. Create a new Java Main Class named Addition
Step 1. Choose File Type
 Categories: Java, Files Types: Java Main Class
Step 2. Name and Location
 Class Name: Addition

5
import javax.swing.JOptionPane;

public class Addition {

public static void main(String[] args) {


String firstNumber = JOptionPane.showInputDialog
( "Enter first integer");
String secondNumber = JOptionPane.showInputDialog
("Enter second integer");

int firstInt = Integer.parseInt(firstNumber);


int secondInt = Integer.parseInt(secondNumber);

int sum = firstInt + secondInt;

JOptionPane.showMessageDialog(null, "The sum is " + sum);


}
}

6
JOptionPane Dialogs
A dialog is normally used as a temporary window
to receive additional information from the user, or
to provide notification that some event has
occurred.

A JOptionPane
dialog can display
an icon, a message,
an input, and option
buttons.

7
Message Dialogs
A message dialog box simply displays a message to
alert the user and waits for the user to click the OK
button to close the dialog.
JOptionPane.showMessageDialog(null, “This is an error",

“Error", JOptionPane.INFORMATION_MESSAGE);

8
Message Types
The messageType is one of the following constants:
JOptionPane.ERROR_MESSAGE
JOptionPane.INFORMATION_MESSAGE
JOptionPane.PLAIN_MESSAGE
JOptionPane.WARNING_MESSAGE
JOptionPane.QUESTION_MESSAGE
Input Dialogs
An input dialog box is used to receive input from the user.

10
Confirmation Dialogs
A message dialog box displays a message and waits for
the user to click the OK button to dismiss the dialog.
The message dialog does not return any value. A
confirmation dialog asks a question and requires the
user to respond with an appropriate button. The
confirmation dialog returns a value that corresponds
to a selected button.

11
Confirmation Dialogs
JOptionPane..showConfirmDialog(null,message,
title,optionType)
Where optionType can be:
– JOptionPane.YES_NO_OPTION
– JOptionPane.YES_NO_CANCEL_OPTION
– JOptionPane.OK_CANCEL_OPTION
showConfirmDialog returns an int according to the selected option:
– JOptionPane.YES_OPTION
– JOptionPane.NO_OPTION
– JOptionPane.CANCEL_OPTION
– JOptionPane.Ok_OPTION
– JOptionPane.CLOSED_OPTION
12
Good UI Design
• Consistency.
– Consistent user interfaces enable a user to learn
new applications faster.
– Use sentence-style capitalization for prompts in an
input dialog.
– Use book-title capitalization for the title bar of a
window.

13
Introduction to GUI Components
• GUIs are built from GUI components.
• Creating a GUI requires creativity and
knowledge of how GUI components work.

14
GUI Components
• A.k.a. controls or widgets (window gadgets).
Frames Windows that can include a title bar, menu bar and
Maximize, Minimize, and Close buttons.
Containers Interface elements that can hold other components.
Buttons Clickable regions with text or graphics indicating their
purpose.
Labels Text or graphics that provide information.
Text fields Windows that accept keyboard input and allow text to
Text areas be edited.
Drop-down Groups of related items that can be selected from
lists drop-down menus or scrolling windows.
Check boxes Small boxes or circles that can be selected or
Radio buttons deselected.
15
Packages for GUI Programming
Package Type of Classes
javax.swing GUI components such as labels, text fields,
buttons, etc. When you use a Swing
component, you work with objects of that
component’s class. You create the component
by calling its constructor and then call methods
of the component as needed for proper setup.
java.awt The Abstract Windowing Toolkit

java.awt.event Event-handling classes that handle user input.

16
The Java GUI API – 3 groups

Component Container Helper classes


classes classes

•17
GUI Class Hierarchy
Dimension Classes in the java.awt
LayoutManager package
Heavyweight
Font 1

FontMetrics

Object Color Panel Applet JApplet

Graphics

Component Container Window Frame JFrame


*
Dialog JDialog

JComponent Swing Components


in the javax.swing package

Lightweight

18
Component Classes
• An instance of Component can be displayed
on the screen.

19
Swing Components
• All Swing components are subclasses of the
abstract class JComponent.
• JComponent include methods to
o Set the size of a component
o Change the background color
o Define the font used for any displayed text
o Set up ToolTips – explanatory text that appears
when the mouse pointer is over the component.

20
Swing GUI Components
JCheckBoxMenuItem

JMenuItem JMenu

AbstractButton JButton JRadioButtonMenuItem

JToggleButton JCheckBox

JRadioButton
JComponent JEditorPane

JTextComponent JTextField JPasswordField

JTextArea

JLabel JList JComboBox JPanel JOptionPane JScrollBar JSlider

JTabbedPane JSplitPane JLayeredPane JSeparator JScrollPane JRootPane

JToolBar JMenuBar JPopupMenu JFileChooser JColorChooser JToolTip

JTree JTable JTableHeader JInternalFrame JProgressBar JSpinner

21
Common Features of Swing Components
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
java.awt.Component
-font: java.awt.Font The font of this component.
-background: java.awt.Color The background color of this component.
-foreground: java.awt.Color The foreground color of this component.
-preferredSize: Dimension The preferred size of this component.
-visible: boolean Indicates whether this component is visible.
+getWidth(): int Returns the width of this component.
+getHeight(): int Returns the height of this component.
+getX(): int getX() and getY() return the coordinate of the component’s
+getY(): int upper-left corner within its parent component.

java.awt.Container
+add(comp: Component): Component Adds a component to the container.
+add(comp: Component, index: int): Component Adds a component to the container with the specified index.
+remove(comp: Component): void Removes the component from the container.
+getLayout(): LayoutManager Returns the layout manager for this container.
+setLayout(l: LayoutManager): void Sets the layout manager for this container.
+paintComponents(g: Graphics): void Paints each of the components in this container.

The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.JComponent
-toolTipText: String The tool tip text for this component. Tool tip text is displayed when
the mouse points on the component without clicking.
-border: javax.swing.border.Border The border for this component.

22
Creating GUI Objects
// Create a button with text OK
JButton jbtOK = new JButton("OK");

// Create a label with text "Enter your name: "


JLabel jlblName = new JLabel("Enter your name: ");
Label Text Check Radio
field Box Button

Button

// Create a text field with text "Type Name Here" Combo


JTextField jtfName = new JTextField("Type Name Here");
Box
// Create a check box with text bold
JCheckBox jchkBold = new JCheckBox("Bold");

// Create a radio button with text red


JRadioButton jrbRed = new JRadioButton("Red");

// Create a combo box with choices red, green, and blue


JComboBox jcboColor = new JComboBox(new String[]{"Red”,"Green", "Blue"});

23
Container Classes
• An instance of Container can hold
instances of Component.

24
Container Classes

Dimension Classes in the java.awt


LayoutManager package
Heavyweight
Font 1

FontMetrics

Object Color Panel Applet JApplet

Graphics

Component Container Window Frame JFrame


*
Dialog JDialog

JComponent JPanel Swing Components


in the javax.swing package

Lightweight

25
GUI Container Classes
Container Class Description
java.awt.Container Used to group components. Frames,
panels, and applets are its subclasses.
javax.swing.JFrame A window not contained inside another
window. Used to hold other GUI
components.
javax.swing.JPanel An invisible container that holds UI
components. Panels can be nested.
javax.swing.JApplet A base class for creating a Java applet.
javax.swing.JDialog A popup window or message box used as
a temporary window to receive
additional info or provide notification
that an event has occurred.
26
GUI Helper Classes
Dimension Classes in the java.awt
LayoutManager package
Heavyweight
Font 1

FontMetrics

Object Color Panel Applet JApplet

Graphics

Component Container Window Frame JFrame


*
Dialog JDialog

JComponent JPanel Swing Components


The helper classes are not in the javax.swing package
subclasses of Component. They are
used to describe the properties of
GUI components such as graphics Lightweight

context, colors, fonts, and


dimension. 27
Some GUI Helper Classes
Container Class Description
java.awt.Color Deals with colors of GUI components,
e.g. to specify background or
foreground colors.
java.awt.Font Specifies fonts for the text.
java.awt.FontMetrics An abstract class used to get the
properties of the fonts.
java.awt.Dimension Encapsulates the width and height of a
component in a single object.
java.awt.LayoutManager Specifies how components are
arranged in a container

28
Creating a User Interface
• The first step in creating a GUI application is to
create a class that represents the graphical user
interface.
• An object of this class serves as a container that
holds the components to be displayed.
 You need to create a frame to hold the GUI
components.

29
Frames
• A window for holding other GUI components.
It is a window that is not contained inside
another window.
• To create a frame, use the JFrame.

30
JFrame Class
javax.swing.JFrame
+JFrame() Creates a default frame with no title.
+JFrame(title: String) Creates a frame with the specified title.
+setSize(width: int, height: int): void Specifies the size of the frame.
+setLocation(x: int, y: int): void Specifies the upper-left corner location of the frame.
+setVisible(visible: boolean): void Sets true to display the frame.
+setDefaultCloseOperation(mode: int): void Specifies the operation when the frame is closed.
+setLocationRelativeTo(c: Component): Sets the location of the frame relative to the specified component.
void If the component is null, the frame is centered on the screen.
+pack(): void Automatically sets the frame size to hold the components in the
frame.

JFrame is a top-level container to hold GUI components

31
A. Open your Chapter1 NetBeans project
B. Create a new Java Main Class named MyFrame
Step 1. Choose File Type
 Categories: Java, Files Types: Java Main Class
Step 2. Name and Location
 Class Name: MyFrame

•32
import javax.swing.*;

public class MyFrame extends JFrame {


public MyFrame() {
super("Frame Title");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}

public static void main(String[] args) {


MyFrame myFrame = new MyFrame();
}
}

33
Method: Creating a Swing application
• Make the user interface a subclass of JFrame.
• The constructor of the class should include the
following tasks:
1. Call a superclass constructor to give the frame a title
and handle other setup procedures.
2. Set the size of the frame’s window.
3. Specify what to do if a user closes the window.
4. Display the frame.

34
JFrame Class
javax.swing.JFrame
+JFrame() Creates a default frame with no title.
+JFrame(title: String) Creates a frame with the specified title.
+setSize(width: int, height: int): void Specifies the size of the frame.
+setLocation(x: int, y: int): void Specifies the upper-left corner location of the frame.
+setVisible(visible: boolean): void Sets true to display the frame.
+setDefaultCloseOperation(mode: int): void Specifies the operation when the frame is closed.
+setLocationRelativeTo(c: Component): Sets the location of the frame relative to the specified component.
void If the component is null, the frame is centered on the screen.
+pack(): void Automatically sets the frame size to hold the components in the
frame.

JFrame is a top-level container to hold GUI components

35
JFrame constants for
setDefaultCloseOperation()’s
arguments
EXIT_ON_CLOSE Exit the application when the frame is
closed.

DISPOSE_ON_CLOSE Close the frame, remove the frame object


from memory, and keep running the
application.
DO_NOTHING_ON_CLOSE Keep the frame open and continue
running.

HIDE_ON_CLOSE Close the frame and continue running.

36
The Frame’s Constructor
• The work involved in creating the frame’s user
interface takes place in its constructor. When
components are created and added to this
frame, it is done within this constructor.

37
Creating a Component
• Each GUI component is represented by its own
class. To create an GUI component in Java,
you create an object of that component’s
class.
– E.g., to create a button, just create an instance of
JButton.

38
To your MyFrame class
• Add a button object

•39
import javax.swing.*;

public class MyFrame extends JFrame {


private JButton jbtOK = new JButton("OK");

public MyFrame() {
super("Frame Title");
add(jbtOK);
...
}
...
}

40
JButton Constructors
The following are JButton constructors:
JButton()
JButton(String text)
JButton(String text, Icon icon)
JButton(Icon icon)

•41
Review of Lesson Objectives
You should now be able to:
• Create a simple application using dialog boxes.
• Describe what are components and containers in a
graphical user interface.
• Create a GUI application class by extending the
JFrame class.
Chapter 1
GUI Components I – Part 2
How to you lay out GUI
components in a container?

Use a
layout
manager

44
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
• Create image icons using the ImageIcon class
45
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
container’s layout manager.
• There are several different layout managers that
you can choose from to place components in the
desired locations.

46
•46
3 Basic Layout Managers
• FlowLayout
• GridLayout
• BorderLayout
Note: By default, the frame’s layout is BorderLayout.

47
•47
Creating and Setting Layout Managers
• A layout manager is created using a layout
manager class.
eg
LayoutManager mgr = new FlowLayout();
• Every layout manager class implements the
LayoutManager interface.
• You can set the layout manager for a container
using the setLayout(LayoutManager)
method.

48
•48
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 are
automatically rearranged to fit in it.

49
•49
A. Open your Chapter1 NetBeans project
B. Create a new Java Main Class named
ShowFlowLayout to create the following GUI:

•50
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));

51
setTitle("ShowFlowLayout");
setSize(200, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


ShowFlowLayout frame = new ShowFlowLayout();
}
}

52
The FlowLayout Class

The get and set methods for these data fields are provided in
java.awt.FlowLayout 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: Creates a FlowLayout manager with a specified alignment,
int, vgap: int) horizontal gap, and vertical gap.

53
•53
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.

54
•54
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.

55
•55
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.
•56
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));
57
setTitle("ShowGridLayout");
setSize(250, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


ShowGridLayout frame = new ShowGridLayout();
}
}
Question:

Replace setSize(250,150) with pack().


What is the effect? 58
The GridLayout Class
The get and set methods for these data fields are provided in
java.awt.GridLayout 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 container.
59
•59
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. 60
•60
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.
•61
The BorderLayout Class

The get and set methods for these data fields are provided in
java.awt.BorderLayout 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.

62
•62
Additional Methods for Layout Managers
FlowLayout GridLayout BorderLayout

setAlignment(value); setRows(value); setHgap(value);


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

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

63
•63
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
64
•64
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.

65
•65
Using Panels as Subcontainers
• A frame can contain panels and UI components. Panels
are used to group user-interface components.
• Panels can contain other panels.

E.g. Frame
Panel
User interface
components (UI)

Panel Panel Panel

UI UI UI

66
•66
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);

67
•67
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.
•68
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"));

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


controlPanel.add(new JTextField("Time to be displayed here"),
BorderLayout.NORTH);
controlPanel.add(buttonPanel, BorderLayout.CENTER);
69
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();
}
}

70
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);
71
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.

72
Setting Colors
• You can use the following methods to set the
component’s background and foreground colors:
 setBackground(Color c)
 setForeground(Color c)
• Example:
jbt.setBackground(Color.yellow);
jbt.setForeground(Color.red);

73
In your Chapter1 NetBeans project, create a
new Java Main Class named TestColor.

•74
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)); 75
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();
}
}

76
The Font Class
Font Names Font Style
• Standard font names that • Font.PLAIN (0),
are supported in all Font.BOLD (1),
platforms are: Font.ITALIC (2),
SansSerif, Serif, and Font.BOLD +
Monospaced, Dialog, Font.ITALIC (3)
or DialogInput.

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


Example:
Font myFont1 = new Font("SansSerif ", Font.BOLD, 16);
Font myFont2 = new Font("Serif", Font.BOLD+Font.ITALIC, 12);

JButton jbtOK = new JButton("OK“);


jbtOK.setFont(myFont1);

77
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]);

78
In your Chapter1 NetBeans project, create a
new Java Main Class named TestFont.

•79
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));

80
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);

}
}
81
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)
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 TitledBorder(“My Panel”));

82
Test Swing Common Features
Component Properties JComponent Properties
• font • toolTipText
• background • border
• foreground
• preferredSize
• minimumSize
• maximumSize

83
In your Chapter1 NetBeans project, create a
new Java Main Class named
TestSwingCommonFeatures.

•84
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");
85
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);

86
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);
}
87
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"));

88
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.
•89
setTitle("TestImageIcon");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 100);
setVisible(true);
}
public static void main(String[] args) {
new TestImageIcon();
}
}

90
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 reason, Swing
components that don’t rely on native GUI are referred to as lightweight
components, and AWT components are referred to as heavyweight components.
91
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
• Create image icons using the ImageIcon class

You might also like