0 ratings 0% found this document useful (0 votes) 66 views 48 pages Chapter 1 Intro To GUI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save Chapter 1 Intro to GUI For Later AACS3094
GUI AND WEB APPLICATION
PROGRAMMING
&
uy NetBeans =
Java
Introduction to GUI — Part 1
Chapter 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.Introduction
* A graphical user interface (GUI) makes a
system user-friendly and easy to use.
* NetBeans IDE Java Quick Start Tutorial
ahi]
Downloadkb.comDialog 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.
{Fotiow
A. Create a new NetBeans project named Chapter1
Q)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: Additionimport javax.swing.JOptionPane;
public class Addition {
public static void main(String[] args) {
String firstNumber = JOptionPane.show!nputDialoa("Enter first
integer”);
String si = JOptionPane.s utDialoa("Enter
second integet
int firstint = Integer. parselnt(firstNumben;
int secondint
int sum = firs
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.
AdJOptionPane
dialog can display
Input an icon, a message,
an input, and option
buttons.
Icon’ Message
ButtonsMessage 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. ERROR MESSAGE
ICON
import javax.swing.JOptionPane;
public class dialogmessage {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,
"Eggs are not supposed to be green.",
"Inane warning",
JOptionPane.WARNING_MESSAGE);
}
}Message Types
The messageType is one of the following constants:
OptionPane.ERROR_MESSAGE
JOptionPane. INFORMATION MESSAGE
JoptionPane. PLAIN_MESSAGE
JoptienPane.WARNENG MESSAGE
JoptichPane QUESTION WESSAGE |
Input Dialogs
An input dialog box is used to receive input from the user.
x
ge
I
om] | canceConfirmation 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.
SE | (S| [S|
Dy conten DB concen D) conten
ves | | No [ies ]|_ no || cancer OK | cancel
ConfirmationDialog
import javax.swing.JOptionPane;
public class ConfirmationDialog {
public static void main(String[] args) {
int n = JOptionPane.showConfirmDialog(null,“YES
OR NO",“Message",
JOptionPane.YES_NO_OPTION);
}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.
Modal Dialog
* Each JOptionPane dialog that you display
is a modal dialog — while the dialog is on the
screen, the user cannot interact with the rest
of the application.
* Do not overuse modal dialogs as they can
reduce the usability of your applications. Use
them only when it’s necessary to prevent
users from interacting with the rest of the
application until they dismiss the dialog.Introduction to GUI Components
* GUls are built from GU! components.
* Creating a GUI requires creativity and
knowledge of how GUI components work.
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.Coming up next
* The following section provides a brief overview
of the Java GUI API.
* A detailed coverage will be covered much later.
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.
The Java GUI API — 3 groups
jee)
oS!
=
Component Container Helper classes
classes classesSwing 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.
GUI Class Hierarchy
Dimension
Font T
Fonitferics
Object
Color Panel Applet
Graphics
Frame
‘Component Container Kf Window [ Frame
Dialog DialComponent Classes
+ An instance of Component can be displayed
on the screen.
JButton
‘Component
Swing GUI Components
| fresco} fea)
[Component] Kt Baio
——,
=
E
(Gicotber] — Giteaier)] GRopapNteme] ritechooser] [FGolerChooser] [ToolTipCommon Features of Swing Components
freon vast Cor
refer: Denon
[srmeovisc nner
Creating GUI Objects
I create
jpe
button with ©
= new dButto
eate a label with text “Enter your name
new JLabel ("Enter
abel Text Check Radio
field Box Button
fatale
Button on eeryournane oe ree) at Re [Ra ~)
// Create a text £: with text "Type Name Her: Gey
IextField jtfllame = new JTextField("Type Name Here"); Box
// Create a check box with text
IcheckBox jchkBold = new JCheckBox |"
/{ Create a radio button with text red
JRadioButton jrbRed = new JRadioButton ("Red");
// Create a
fonboBox jel
3 red,
olor = new JComboBo:
ren, and
teing(](Container Classes
¢ An instance of Container can hold
instances of Component.
Container Classes
i ‘Dimension Tr Classes in the java.awt |
| eae a 7
= 7
| Lin 7
Onet KH [enor Pan Tae KH] |
| eres Itt I
| cu I
Cc |_|
Component} [Comer Wate Kreme KH are] |
|e Kt [ t \
| Dame KP} pate] |
| bak 4
a — —
hciGUI Container Classes
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 Ul
components. Panels can be nested.
javax.swing.JApplet A base class for creating a Java applet.
javax. swing. Dialog A popup window or message box used as.
a temporary window to receive
additional info or provide notification
that an event has occurred.
GUI Helper Classes
| ‘Dimension | Classes inthe javaawt |
Ta a=
| Hoe 7 |
| Homememes i -
7
One KHL Corer Pan vane KH ia] |
' '
caphes
| Les ||
compe Waser KE Dime KHL rey |
as li ci !
Dialog LL pipae] |
; LJ Pye J
a = = Componeny Panel Sing Componente
‘The helper classes are not
subclasses of Component. They are
used to describe the properties of
GUI components such as graphics Lisi
context, colors, fonts, and
dimension.Some GUI Helper Classes
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
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. The next section introduces frames.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.
JFrame Class
-+3Frameg) Creates a default frame with no ttl,
+JFramettle: String) Creates a frame with the specified tile,
sor Sizo(width: int, height: int): void Specifies the size ofthe frame,
$setLocation(s: int y: it): void Specifies the upper-leRt comer location of the frame,
}+setVisible(visible: boolean): void Sets true to display the frame.
+sctDefaultCloseOperation(mode: int): void | Specifies the operation when the fram: is closed,
‘setLocationRelativeTo(e: Component): | Sets the location of the frame relative tothe specified component
void the component is null, the frame is centered on the screen,
+pack0: void Automatically sets the frame size to hold the components in the
frame,
JFrame is a top-level container to hold GUI componentsFoliow
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
import javax.swing.JFrame;
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();
}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 asuperclass constructor to give the frame a title
and handle other setup procedures.
2. Set the size of the frame’s window.
Specify what to do if a user closes the window.
4. Display the frame.
w
JFrame Class
-+3Frameg) Creates a default frame with no ttl,
+JFramettle: String) Creates a frame with the specified tile,
sor Sizo(width: int, height: int): void Specifies the size ofthe frame,
$setLocation(s: int y: it): void Specifies the upper-leRt comer location of the frame,
}+setVisible(visible: boolean): void Sets true to display the frame.
+sctDefaultCloseOperation(mode: int): void | Specifies the operation when the fram: is closed,
‘setLocationRelativeTo(e: Component): | Sets the location of the frame relative tothe specified component
void the component is null, the frame is centered on the screen,
+pack0: void Automatically sets the frame size to hold the components in the
frame,
JFrame is a top-level container to hold GUI componentsJFrame 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.
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.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.
{Fotiow:
To your MyFrame class
° Add a button objectimport javax.swing.JButton;
import javax.swing.JOptionPane;
public class MyFrame extends JFrame {
private JButton jbtOK = new JButton("OK");
public MyFrame() {
super("Frame Title");
add(jbtOk);
JButton Constructors
The following are JButton constructors:
JButton ()
JButton (String text)
JButton (String text, Icon icon)
JButton (Icon icon)Adding Components to a Container
To add a component to a container, call the
container’s add (Component) method with
the component as the argument
(all GUI components in Swing inherit from
java.awt.Component).
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.Introduction to GUI — Part 2
Chapter 1
How Do you /ay out GUI
components in a container?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
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.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.
3 Basic Layout Managers
° FlowLayout
°* GridLayout
* BorderLayout
Note: By default, the frame’s layout is BorderLayout.
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
© Ifyou do not specify the alignment, center alignment is used.
* Ifyou resized the frame, the components are
automatically rearranged to fit in it.Fotiow.
A. Open your Chapter1 NetBeans project
B. Create a new Java Main Class named
ShowFlowLayout to create the following GUI:
Caen
import javax.swing.JLabel;
import javax.swing.J TextField;
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();
The FlowLayout Class
java.awt FlowLayout
alignment: int The alignment of this layout manager (default: CENTER),
-hgap: int ‘The horizontal gap of this layout manager (default; 5 pixels),
-ygap: 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: {f Creates a FlowLayout manager with a specified alignment,
int, veap: int) horizontal gap, and vertical gap.Introduction to GridLayout
e 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.
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.@ 2
In your Chapter1 NetBeans project, create a new Java
Main Class named ShowGridLayout to create the
following GUI: [Becca ae el lea)
Note
© Ifyou resize the frame, the layout of the components remains
unchanged.
© All components are given equal size in the container of
GridLayout.
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));setTitle("ShowGridLayout");
setSize(250, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
7
public static void main(String[] args) {
ShowGridLayout frame = new ShowGridLayout();
}
The GridLayout Class
rows: int ‘The number of os in this layout manager (default 1,
columns: int The number of columns in this layout manager (default: 1,
gap: int The horizontal gap of this layout manager (default: 0).
-veap: int ‘The vertical gap of this layout manager (default: 0).
Creates a default GridLayout manager,
-+Gridlayout(rows: int, columns: int) | Creates a GridLayout with a specified number of rows andl columns.
+GridLayout(rows: int, columns: int, | Creates a GridLayout manager with a specified number of rows and
hhgap: int, veap: int) columns, horizo 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.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.
@4
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.import javax.swing.*;
import java.awt.BorderLayout;
port java.awt.HeadllessException;
public class ShowBorderlayout extends IFrame {
public ShowBorderLayout() {
setLayout(new BorderLayout(5, 10));
add(new JButton("East"), BorderLayout.FAST);
add(new JButton("West"), BorderLayout.WEST);
add(new JButton("North”), BorderLayout.NORTH);
add(new JButton("South"), BorderLayout SOUTH);
add(new JButton("Center"), BorderLayout.CENTER);
setTitle("BorderLayout");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.&XIT_ON_CLOSE);
setSize(300, 200};
setVisible(true);
}
public static void main(Stringl] args) {
new ShowBorderLayout();
}
}
The BorderLayout Class
Ids are provided in
ram for by
Javaawt,BorderLavout
The horizontal gap of this layout manager (default: 0).
The vertical gap of this layout manager (default: 0)
*BorderLayout) Creates a default BorderLayout manager.
}+BorderLayout(hgap: int, ygap: int) ff 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 spaceAdditional Methods for Layout Managers
FlowLayout Gridiayout BorderLayout,
‘setAlignment (value) ; setRows (value); setligap (value) ;
settigap (value) ; setColumns (value); | setVgap (value);
setVgap (value) ; aed
setVgap (value) ;
Eg:
FlowLayout flowlayout = new FlowLayout () ;
flowlayout.setAlignment (FlowLayout.RIGHT) ;
flowlayout. setHgap (10) ;
flowlayout. setVgap (20) ;
Suppose you want to design an interface as follows:
] eet o
[Time to be displayed here
1 2 3
4 5 6
Food to be placed here!
7 8 9
° start | stop
* It is difficult to achieve the desired
look by placing all the components in a
single container.Alergy)
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.
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.
Eg.
Frame,
Panel
User interface
components (UI)
Panel Panel Panel
UlSteps for Using Panels
1. Create a panel object p1:
JPanel pl = new JPanel () ;
2. Add a GUI component to the panel p1:
pl.add(new JButton(“ButtonName”) ) ;
3. Place the panel into the container as follows:
add (pl) ;
or, place the panel into another panel:
JPanel p2 = new JPanel ();
p2.add(p1) ;
a
In your Chapter1 NetBeans project, create a new
Java Main Class named TestPanels to create the
following GUI:
Food tobe placed here|
Note: We can also set the layout manager for a panel.
e By default, JPanel uses FlowLayout.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 = 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);
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();
} ) #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);
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.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) ;
bt. setForeground (Color. red) ;
@ 3
In your Chapter1 NetBeans project, create a
new Java Main Class named TestColor.
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("Nort!
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));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();
}
}
The Font Class
Font Names Font Style
* Standard font names that
are supported in all
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 myFont = new Font("SansSerif ", Font.BOLD, 16);
Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12);
Button jbtOK = new JButton("OK) ;
jbtOK. setFont (myFont) ;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]) ;
@ 3
In your Chapter1 NetBeans project, create a
new Java Main Class named TestFont.
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.getAvailableF ontFamilyNames();
setLayout(new FlowLayout());
JButton]] buttonArray = new JButton[fontNames.length];
add(new JLabel("Total fonts: " + fontNames.length));for (int i = 0; i < fontNames.length; ++i) {
buttonArray[i] = new JButton((i+1) +". " + fontNames{i]);
if (1% 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);
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”) ) ;Test Swing Common Features
Component Properties JComponent Properties
* font + toolTipText
background E pocder
foreground
@ m
preferredSize
minimumSize
maximumSize
In your Chapter1 NetBeans project, create a
new Java Main Class named
TestSwingCommonFeatures.
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");p1.add(jbtLeft);
p1.add(btCenter);
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 jlbIRed = new JLabel("Red");
JLabel jlbIOrange = new JLabel("Orange");
jlbIRed.setForeground(Color.RED);
jlblOrange.setForeground(Color.ORANGE);
jlbIRed.setFont(largeFont);
jlblOrange.setFont(largeFont);
jlbIRed.setBorder(lineBorder);
jlblOrange.setBorder(lineBorder);
p2.add(jIbIRed);
p2.add(jIblOrange);
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);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")) ;
‘Fetow ne!
In your Chapter1 NetBeans project window,
1. Right-click the Source Packages node and choose New
> Java Package
2. Inthe Package Name text field, replace newpackage
with images.
3. Click Finish.
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
Testimagelcon.import java.awt.*;
import javax.swing.*;
public class Testimagelcon extends JFrame {
private Imagelcon uslcon = new
Imagelcon(getClass().getResource("images/us.gif"));
private Imagelcon mylcon = new
Imagelcon(getClass().getResource("images/my.jpg"));
private Imagelcon fricon = new
Imagelcon(getClass().getResource("images/fr.gif"));
private Imagelcon ukicon = new
Imagelcon(getClass().getResource("images/uk.gif"));
public TestImagelcon() {
setLayout(new GridLayout(1, 4, 5, 5));
add(new JLabel(usicon));
add(new JLabel(mylcon));
add(new JButton(fricon));
add(new JButton(ukicon));
setTitle("TestImagelcon");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 100);
setVisible(true);
}
public static void main(String[] args) {
new Testlmagelcon();
}For simple GUI For comprehensive GUI projects
Heavyweight components Lightweight components.
* Relies heavily on underlying * Less dependent on the target
platform platform
* painted directly on canvases
using Java code
Prone to platform-specific More robust, versatile, flexible
bugs
GuaranteedSwing vs. AWT
So why do the GUI component classes have a prefix J? Instead of JButton, why
not name it simply But ton? 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 GU!
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.
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