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

Java chapter 3

Chapter Three covers GUI programming objectives, including the creation of user interfaces using Java's GUI API hierarchy, layout managers, and basic components. It distinguishes between AWT and Swing, highlighting Swing's advantages such as platform independence and lightweight components. The chapter also details layout managers like FlowLayout, GridLayout, and BorderLayout, as well as the use of colors and fonts in GUI applications.

Uploaded by

amanhabtamu32
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java chapter 3

Chapter Three covers GUI programming objectives, including the creation of user interfaces using Java's GUI API hierarchy, layout managers, and basic components. It distinguishes between AWT and Swing, highlighting Swing's advantages such as platform independence and lightweight components. The chapter also details layout managers like FlowLayout, GridLayout, and BorderLayout, as well as the use of colors and fonts in GUI applications.

Uploaded by

amanhabtamu32
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Chapter Three

GUI Programming
Objectives:
Ø To distinguish simple GUI components.
Ø To describe the Java GUI API hierarchy.
Ø To create user interfaces using frames, panels,
and simple UI components.
Ø To understand the role of layout managers
Ø To use the FlowLayout, GridLayout, and
BorderLayout managers to layout components in a
container.
Ø To specify colors and fonts using the Color and
Font classes.
1
Ø To use JPanel as subcontainers.
GUI Examples

2
G r a p h i c a l User I n t e r f a c e s (GUIs)

⚫ Graphical User Interfaces (GUIs)


⚫ provides user-friendly human interaction
⚫ they were the initial motivation for object-oriented programming
⚫ predefined classes for GUI components, event processing interfaces
⚫ Building GUIs require use of GUI frameworks:
⚫ JavaFX (part of JSE 8, 2014)
⚫ Older Java frameworks:
⚫ Abstract Window Toolkit (AWT):
⚫ java.awt.*, java.awt.geom.*,
java.awt.event.*
⚫ SWING:
⚫ javax.swing.*, javax.swing.event.*

3
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:"); Text Check Radio
field Box Butto
Label
n

Button

Combo
// Create a text field with text "Type Name Here"
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"});
4
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).
AWT is fine for developing simple graphical user interfaces, but
not for developing comprehensive GUI projects.
Besides, AWT is prone/suffered/ 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.
5
For this reason, Swing components that don’t rely on native GUI
are referred to as lightweight components, and AWT components are
Swing vs. AWT
Java AWT Java Swing
A W T c o m p o n e n t s a r e p l a t f o r m - Java swing components are
dependent. platform-independent.
Swing components are
AWT components are heavyweight.
lightweight.
AWT doesn't support pluggable look Swing supports pluggable look
and feel. and feel.
Swing provides more powerful
AWT provides less components than components such as tables,
Swing. lists, scrollpanes,
colorchooser, tabbedpane etc.
AWT doesn't follows MVC(Model View
Controller) where model represents
data, view represents presentation Swing follows MVC.
and
6 controller acts as an interface
between model and view.
GUI Class Hierarchy (Swing
and AWT)

7
The Java GUI API
 The GUI API contains classes that can be
classified into three groups: Component classes,
Container classes, and Helper classes.
 Component Classes: Component classes are
elementary GUI entities, such as JButton, JLabel,
JTextField etc.
 Container Classes: The classes, such as JFrame,
JPanel, and JApplet, JDialog are called container
classes used to contain other components.
 Helper Classes: The classes, such as Graphics,
Color, Font, FontMetrics, and Dimension and
LayoutManager, are called helper classes used to
support GUI components.
8 Component is the root class of all the user-
Container Classes

9
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 subclasses of in the javax.swing package
Component. They are used to describe
the properties of GUI components such
as graphics context, colors, fonts, and
Lightweight
10 dimension.
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


11
AWT (Optional)
AWTEvent Container Panel Applet

Font Button Window Frame

FontMetrics Label Dialog FileDialog


TextField
Object Color TextComponent

TextArea
Graphics List

Component Choice

CheckBox

LayoutManager CheckBoxGroup

Canvas

MenuComponent MenuItem Menu

MenuBar
Scrollbar
12
Swing - Basic Components
 A Strategy for Designing GUI
 Identify needed components
 Choose layout managers
 FlowLayout
 GridLayout
 BorderLayout
 Sketch the GUI

13
Swing - Basic Components
 Category of components
1.Container components
2.Ordinary components
3.Menu components

14
Swing - Basic Components
1. Container Components
 JFrame
 Jpanel
 Japplet
 JDialog

15
JFrame
 Is an independent window that can be moved
around on the screen independently of any other
GUI windows.
 Frame is a window that is not contained inside
another window.
 Frame is the basis to contain other user
interface components in Java GUI applications.
 The JFrame class can be used to create windows.
 For Swing GUI programs, use JFrame class to
create widows.

16
Creating JFrame…
import javax.swing.JFrame;
public class Simple extends JFrame {
public Simple() {
setSize(300, 200);
setTitle("First JFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
Simple simple = new Simple();
simple.setVisible(true);
}
}

17
JFrameClass
JFrame Class

18
JPanel
 A container can be placed inside another
container.
 Panels can be used as sub-containers to group
GUI components to achieve the desired layout.
 Panel is a blank rectangular component that can
contain other components.
 Each panel uses a layout manager to determine
the position and size of its child components.
 It is recommended that you place the user
interface components in panels and place the
panels in a frame.
 You can also place panels in a panel.
19
JPanel
 To add a component to JFrame, you actually add
it to the content pane of JFrame.
 To add a component to a panel, you add it
directly to the panel using the add method.
• You can use new JPanel() to create a panel with
a default FlowLayout manager or new
JPanel(LayoutManager) to create a panel with
the specified layout manager.
• Use the add(Component) method to add a
component to the panel.
• For example, JPanel p = new JPanel();
20
p.add(new JButton("OK"));
Creating a JPanel Interface - Example

frame
A textfield
p2
A button 12
buttons p1

21
Layout Managers
 Each container contains a layout manager, which
is an object responsible for laying out the GUI
components in the container

 Java’s layout managers provide a level of


abstraction to automatically map your user
interface on all window systems.

 The UI components are placed in containers.


Each container has a layout manager to arrange
the UI components within the container.

22 Layout managers are set in containers using the


Types of Layout Managers
 There are three basic layout managers in
Java.

1. FlowLayout

2. GridLayout

3. BorderLayout

23
The FlowLayout Manager
 FlowLayout is the simplest layout manager.
 The components are arranged in the container from
left to right in the order in which they were
added.
 When one row is filled, a new row is started.
 You can specify the way the components are aligned
by using one of three constants:
 FlowLayout.RIGHT,
 FlowLayout.CENTER, or
 FlowLayout.LEFT.

24
FlowLayout - Example
Write a program that adds three labels and
text fields into the content pane of a frame
with a FlowLayout manager.

25
FlowLayout - Example
 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));
}
public static void main(String[] args) {
ShowFlowLayout frame = new ShowFlowLayout();
frame.setTitle("ShowFlowLayout");
frame.setSize(200, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
26 }
FlowLayout Class Diagram
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.

27
The GridLayout Manager
• The GridLayout manager arranges components in a
grid (matrix) formation.
• 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.
Example: Rewrite the program in the preceding
example using a GridLayout manager instead of a
FlowLayout manager to display the labels and
text fields.

28
GridLayout - Example
 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, 5, 5));
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));
}
public static void main(String[] args) {
ShowGridLayout frame = new ShowGridLayout();
frame.setTitle("ShowGridLayout");
frame.setSize(200, 125);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
29
}
GridLayout Class Diagram

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.

30
The BorderLayout Manager
• The BorderLayout manager divides the
container into five areas: East, South, West,
North, and Center.
• Components are added to a BorderLayout by
using the add method.
• add(Component, index), where index is a
constant BorderLayout.EAST,
BorderLayout.SOUTH, BorderLayout.WEST,
BorderLayout.NORTH, or
BorderLayout.CENTER.
31
BorderLayout - Example

Writer program adds five buttons labeled East,


South, West, North, and Center to the frame with
a BorderLayout manager

32
BorderLayout - Example
 import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.BorderLayout;
public class ShowBorderLayout extends JFrame {
public ShowBorderLayout() {
setLayout(new BorderLayout(5, 10));
add(new JButton("East"), BorderLayout.EAST);
add(new JButton("South"), BorderLayout.SOUTH);
add(new JButton("West"), BorderLayout.WEST);
add(new JButton("North"), BorderLayout.NORTH);
add(new JButton("Center"), BorderLayout.CENTER);
}
public static void main(String[] args) {
ShowBorderLayout frame = new ShowBorderLayout();
frame.setTitle("ShowBorderLayout");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
33 }
}
BorderLayout Class Diagram

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.

34
The Color Class
• Each GUI component has background and
foreground colors.
• Colors are objects created from 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 represented by an int value
that describes its intensity, ranging from 0
(darkest shade) to 255 (lightest shade).
• This is known as the RGB model.
35
Color c = new Color(r, g, b); r, g, and b
Standard Colors
• Thirteen standard colors (black, blue, cyan,
darkGray, gray, green, lightGray, magenta,
orange, pink, red, white, yellow) are
defined as constants in java.awt.Color.
• You can use the following methods to set the
component’s background and foreground colors:
setBackground(Color c)
setForeground(Color c)

Example: JButton jbt = new JButton("OK");


jbt.setBackground(Color.yellow);

36
jbt.setForeground(Color.red);
The Font Class
 Each GUI component has the font property.
 Fonts are objects created from the Font class.
 You can create a font using the java.awt.Font class
and set fonts for the components using the setFont
method in the Component class.
Font Names Font Style
Standard font names that are Font.PLAIN (0), Font.BOLD
supported in all platforms are: (1), Font.ITALIC (2), and
SansSerif, Serif, Monospaced, Font.BOLD + Font.ITALIC (3)
Dialog, 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);

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


jbtOK.setFont(myFont);
Finding All Available Font
Names
• To find the fonts available on your system, you need to obtain an
instance of java.awt.GraphicsEnvironment using its static
method getLocalGraphicsEnvironment().
• GraphicsEnvironment is an abstract class that describes the
graphics environment on a particular system.
• You can use its getAllFonts() method to obtain all the available
fonts on the system and its getAvailableFontFamilyNames()
method to obtain the names of all the available fonts.
• Example:

GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();
for (int i = 0; i < fontnames.length; i++)
38 System.out.println(fontnames[i]);
Common Features of Swing Components
T h e get an d set m eth od s for th ese d ata field s are p rovid ed in
th e class, b ut om itted in th e U M L d iagram for b revity.
ja va .a w t.C o m p o n en t
-fon t: java.aw t.Fon t T h e fon t of th is com p on en t.
-b ack grou nd : java.aw t.C olor T h e b ack grou nd color of th is com p onen t.
-foregrou n d : java.aw t.C olor T h e foregrou n d color of this com p on en t.
-p referred S ize: D im en sion T h e p referred size of th is com p on en t.
-visib le: b oolean In d icates w h eth er this com p on en t is visib le.
+ getW id th (): in t R etu rn s th e w id th of this com p on ent.
+ getH eigh t(): int R etu rn s th e h eigh t of this com p on en t.
+ getX (): in t getX () an d getY () retu rn th e coord in ate of th e com p on en t’s
+ getY (): in t u pp er-left corn er w ithin its p aren t com p on ent.

java.a w t.C o ntainer


+ add (com p : C om p on en t): C om p on ent A d d s a com p on en t to th e contain er.
+ add (com p : C om p on en t, ind ex: in t): C om p on ent A d d s a com p on en t to th e contain er w ith th e sp ecified ind ex.
+ rem ov e(com p : C om p on ent): void R em oves th e com p on ent from th e contain er.
+ getLa you t(): La you tM anager R etu rn s th e layou t m an ager for this con tain er.
+ setLa you t(l: La you tM an ager): void S ets th e layou t m an ager for this con tain er.
+ p ain tC om p on ents(g: G rap h ics): void P aints each of th e com p on en ts in th is con tain er.

T h e get an d set m eth od s for th ese d ata field s are p rovid ed in


th e class, b ut om itted in th e U M L d iagram for b revity.
ja va x.sw in g .JC o m p o n en t
-toolT ip T ext: S trin g T h e tool tip text for this com p on ent. T ool tip text is d isp layed w h en
th e m ou se p oin ts on th e com p on ent w ith ou t clickin g.
39 -b ord er: javax.sw in g.b ord er.B ord er T h e b ord er for th is com p on en t.
ImageIcon Class
• Image icons are objects created using the
I m a g e I c o n c l a s s .
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:
40 ImageIcon icon = new ImageIcon("image/us.gif");
2. Ordinary Components
 Here is Some of the basic JComponents in which the user
directly inputs data
 JLabel
 JButton
 JCheckBox
 JRadioButton
 JScrollBar
 JTextField
 JPasswordField
 JTextArea
 JComboBox
 JTable
 JTree
41
 JSlider
JLabel
 A label is a display area for a short text, an
image, or both.
 With the JLabel class, you can display un-
selectable text and images.
 JFrame frame = new JFrame();
 JLabel label = new JLable(“Name”)
 frame.add(label);

42
JButton
 A button is a component that triggers an action
when clicked.
 There are a few steps in using a button:
declaring it, creating it, adding it to a
container (the content pane or a JPanel),
and adding a listener that has code to
execute when the user clicks on the button.

JButton btn = new JButton(text);


JButton btn = new JButton(text, image);
JButton btn = new JButton(image);
43
JButton

JButton mybtn = new JButton("Do Something");

mybtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doMyAction(); // code to execute when button is pressed
}
}

. . .
JPanel content = new JPanel();
content.add(mybtn); // add the button to a JPanel (eg,content).

44
JCheckBox
 JCheckBox is a widget that has two states. On
and Off.
 It is a box with a label.
 If the checkbox is checked, it is represented
by a tick in a box.
 JCheckBox box = new JCheckBox()

45
JCheckBox…
Constructors
cb = new JCheckBox(text); Creates check box, initially unchecked.

cb = new JCheckBox(text, state); Creates check box, checked or not depending


on state.

Methods
state = cb.isSelected(); Returns true if the check box is checked.

cb.setSelected(state); Checks (true) or unchecks check box.

cb.addActionListener(action-listener); Adds an action listener to the radio button. The


action listener will be called if button is
selected.

cb.addItemListener(item-listener); Add an item listener to a radio button. The


item listener will be called if the button is
selected or deselected.

46
JRadioButton
 Radio buttons are groups of buttons in
which only one button at a time can be
selected.

47
JRadioButton
JRadioButton bird = new JRadioButton("Bird");
JRadioButton cat = new JRadioButton("Cat");
JRadioButton dog = new JRadioButton("Dog");
ButtonGroup bg = new ButtonGroup();
bg.add(bird);
bg.add(cat);
bg.add(dog);

48
JTextField
 A text field can be used to enter or display a
string.

JTextField firstName = new JTextField(20);


JTextField surName = new JTextField(20);
JTextField address = new JTextField(60);
JPanel p=new JPanel();
p.add(firstName);
p.add(surName);
p.add(address);

49
JPasswordField
Password field

JPasswordField userName = new JPasswordField(20);


JFrame f=new JFrame(“Example 01”); //you may use another container
f.add(userName);//adds the password field to a container

50
JTextArea
 A JTextArea enables the user to enter multiple
lines of text Text Area

Effect of Scroll Pane

JTextArea textArea = new JTextArea(5, 20);


JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setEditable(true);
JPanel p=new JPanel();
p.add(scrollPane);

51
JTextArea

52
JComboBox
 A combo box, also known as a choice list or drop-
down list, contains a list of items from which the
user can choose

53
JComboBox
String[] pet = {"Bird", "Cat", "Dog", "Rabbit", "Pig"};
//Create the combo box, select item at index 4.

//Indices start at 0, so 4 specifies the pig.


JComboBox petList = new JComboBox(pet);
petList.setSelectedIndex(4);

54
JList
A list is a component that basically performs the same
function as a combo box, but it enables the user to
choose a single value or multiple values.

String[] str = {"Math", "Computer", "Physics",


"Chemistry"};
JList list=new JList(str);
JPanel p=new JPanel();
p.add(list);

55
JList
 Home work?

List area

Text box

56
3. Menu Components

57
Menu Components
import java.awt.event.*;
import javax.swing.*;
public class MenuComponent extends JFrame{
public MenuComponent(){
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
JMenuItem mi1 = new JMenuItem("Sub Menu 1");
menu.add(mi1);
JMenuItem mi2 = new JMenuItem("Sub Menu 2");
menu.add(mi2);
JMenuItem mi3 = new JMenuItem("Sub Menu 3");
menu.add(mi3);
menuBar.add(menu);
setJMenuBar(menuBar);
}
public static void main(String[] args){
MenuComponent frame = new MenuComponent();
frame.setTitle("Menu Demo");
frame.setSize(400,300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
58 }
JavaFX GUI
Stage
• Basic Structure
Scene

Button
⚫ javafx.application.Application:is the entry point for
JavaFX applications
• JavaFX creates an application thread for running the
application start method, processing input events, and
running animation timelines.
• We override the start(Stage)method!
⚫ javafx.stage.Stageis the top level JavaFX container (i.e.,
window)
• The primary Stage is constructed by the platform.
⚫ javafx.scene.Sceneclass is the container for all content in
a scene graph in the stage.
⚫ javafx.scene.Nodeis the base class for scene graph

9
nodes (i.e., components).

59
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;

public class MyFirstJavaFX extends Application {


@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Create a button and place it in the scene
Button btOK = new Button("OK");
Scene scene = new Scene(btOK, 200, 250);
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.setTitle("MyJavaFX"); // Set the stage title
primaryStage.show(); // Display the stage
}

public static void main(String[] args)


{ launch(args);
}
}

60
// Multiple stages can be added beside the primaryStage
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;

public class MultipleStageDemo extends Application {


@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Create a scene and place a button in the scene
Scene scene = new Scene(new Button("OK"), 200, 250);
primaryStage.setTitle("MyJavaFX"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
Stage stage = new Stage(); // Create a new stage
stage.setTitle("Second Stage"); // Set the stage title
// Set a scene with a button in the stage
stage.setScene(new Scene(new Button("New Stage"), 100, 100));
stage.show(); // Display the stage
}

public static void main(String[] args)


{ launch(args);
}
}

61
Panes, UI Controls, and
Shapes

62
Layout
Panes
⚫JavaFX provides many types of panes for organizing nodes
in a container.

63
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.control.Button;

public class ButtonInPane extends Application {

@Override // Override the start method in the Application class


public void start(Stage primaryStage) {
// Create a scene and place a button in the scene
StackPane pane = new StackPane();
pane.getChildren().add(new Button("OK"));
Scene scene = new Scene(pane, 200, 50);
primaryStage.setTitle("Button in a pane"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}

public static void main(String[] args)


{ launch(args);
}
}

64
FlowPane

65
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.FlowPane; import
javafx.scene.control.Label; import
javafx.scene.control.TextField; import
javafx.geometry.Insets;
public class ShowFlowPane extends Application
{ @Override
public void start(Stage primaryStage) { FlowPane
pane = new FlowPane(); pane.setPadding(new
Insets(11, 12, 13, 14)); pane.setHgap(5);
pane.setVgap(5);
// Place nodes in the pane pane.getChildren().addAll(new
Label("First Name:"),
new TextField(), new Label("MI:"));
TextField tfMi = new TextField();
tfMi.setPrefColumnCount(1);
pane.getChildren().addAll(tfMi, new Label("Last Name:"), new
TextField());
// Create a scene and place it in the stage Scene
scene = new Scene(pane, 210, 150);
primaryStage.setTitle("ShowFlowPane");
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public static void main(String[] args)
{ launch(args);
}
6
}

66
GridPane

1
7

67
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.control.*;
import javafx.geometry.*;
public class ShowGridPane extends Application
{ @Override
public void start(Stage primaryStage) {
// Create a pane and set its properties
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER);
pane.setHgap(5.5);
pane.setVgap(5.5);
// Place nodes in the pane at positions column,row
pane.add(new Label("First Name:"), 0, 0);
pane.add(new TextField(), 1, 0);
pane.add(new Label("MI:"), 0, 1);
pane.add(new TextField(), 1, 1);
pane.add(new Label("Last Name:"), 0, 2);
pane.add(new TextField(), 1, 2);
Button btAdd = new Button("Add Name");
pane.add(btAdd, 1, 3);
GridPane.setHalignment(btAdd, HPos.RIGHT);
// Create a scene and place it in the stage
Scene scene = new Scene(pane);
primaryStage.setTitle("ShowGridPane");
primaryStage.setScene(scene); primaryStage.show(); }
public static void main(String[] args)
1 { launch(args);
8 }}

68
BorderPane

1
9

69
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.control.Label;
import javafx.geometry.Insets;
public class ShowBorderPane extends Application
{ @Override
public void start(Stage primaryStage)
{ BorderPane pane = new BorderPane();
pane.setTop(new CustomPane("Top"));
pane.setRight(new CustomPane("Right"));
pane.setBottom(new CustomPane("Bottom"));
pane.setLeft(new CustomPane("Left"));
pane.setCenter(new CustomPane("Center"));
Scene scene = new Scene(pane);
primaryStage.setScene(scene); primaryStage.show();
}
public static void main(String[] args)
{ launch(args);
}
}
class CustomPane extends StackPane
{ public CustomPane(String title)
{
getChildren().add(new Label(title));
setStyle("-fx-border-color: red");
setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
20 } }

70
Hbox and VBox

2
(c) Paul Fodor and Pearson Inc.
1

71
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class ShowHBoxVBox extends Application
{ @Override
public void start(Stage primaryStage)
{ BorderPane pane = new BorderPane();
HBox hBox = new HBox(15);
hBox.setStyle("-fx-background-color: gold");
hBox.getChildren().add(new Button("Computer Science"));
hBox.getChildren().add(new Button("CEWIT"));
ImageView imageView = new ImageView(new Image("cs14.jpg"));
hBox.getChildren().add(imageView);
pane.setTop(hBox);
VBox vBox = new VBox(15);
vBox.getChildren().add(new Label("Courses"));
Label[] courses = {new Label("CSE114"), new Label("CSE214"),
new Label("CSE219"), new Label("CSE308")};
for (Label course: courses)
{
vBox.getChildren().add(course);
}
pane.setLeft(vBox);
primaryStage.show();
Scene scene = new Scene(pane); primaryStage.setScene(scene);
}

72
Display Shapes

⚫ Programming Coordinate Systems start from the left-upper


corner

2
3

73
Shapes
JavaFX provides many shape classes for drawing texts, lines,
circles, rectangles, ellipses, arcs, polygons, and polylines.

2
(c) Paul Fodor and Pearson Inc.
4

74
Text

75
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.geometry.Insets;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.FontPosture;
public class ShowText extends Application {
@Override
public void start(Stage primaryStage)
{ Pane pane = new Pane();
pane.setPadding(new Insets(5, 5, 5, 5));
Text text1 = new Text(20, 20, "Programming is fun");
text1.setFont(Font.font("Courier", FontWeight.BOLD,
FontPosture.ITALIC, 15));
pane.getChildren().add(text1);
Text text2 = new Text(60, 60, "Programming is fun\nDisplay text");
pane.getChildren().add(text2);
Text text3 = new Text(10, 100, "Programming is fun\nDisplay text");
text3.setFill(Color.RED);
text3.setUnderline(true);
text3.setStrikethrough(true);
pane.getChildren().add(text3);
Scene scene = new Scene(pane, 600, 800);
primaryStage.setScene(scene); primaryStage.show();
}
2 ...
6 }

76
Helper classes: The Color Class

77
Helper classes: The Font Class

78
Line

79
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.scene.paint.Color;
public class ShowLine extends Application
{ @Override
public void start(Stage primaryStage)
{ Pane pane = new Pane();
Line line1 = new Line(10, 10, 10, 10);
line1.endXProperty().bind(pane.widthProperty().subtract(10));
line1.endYProperty().bind(pane.heightProperty().subtract(10));
line1.setStrokeWidth(5);
line1.setStroke(Color.GREEN);
pane.getChildren().add(line1);
Line line2 = new Line(10, 10, 10, 10);
line2.startXProperty().bind(pane.widthProperty().subtract(10));
line2.endYProperty().bind(pane.heightProperty().subtract(10));
line2.setStrokeWidth(5);
line2.setStroke(Color.GREEN);
pane.getChildren().add(line2);
Scene scene = new Scene(pane, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{ launch(args);
}
}

80
Rectangle

81
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import java.util.Collections;
public class ShowRectangle extends Application
{ public void start(Stage primaryStage) {
Pane pane = new Pane();
Rectangle r1 = new Rectangle(25, 10, 60, 30);
r1.setStroke(Color.BLACK);
r1.setFill(Color.WHITE);
pane.getChildren().add(new Text(10, 27, "r1"));
pane.getChildren().add(r1);
Rectangle r2 = new Rectangle(25, 50, 60, 30);
pane.getChildren().add(new Text(10, 67, "r2"));
pane.getChildren().add(r2);
for (int i = 0; i < 4; i++) {
Rectangle r = new Rectangle(100, 50, 100, 30);
r.setRotate(i * 360 / 8);
r.setStroke(Color.color(Math.random(), Math.random(),
Math.random()));
r.setFill(Color.WHITE);
pane.getChildren().add(r);
}
Scene scene = new Scene(pane, 250, 150);
primaryStage.setScene(scene); primaryStage.show();
3 }
2 ...// main

82
Circle

83
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene; Circle in a Pane
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.paint.Color;

 public class ShowCircle extends Application {


 @Override // Override the start method in the Application class public void start(Stage primaryStage) {
 // Create a circle and set its properties Circle circle = new Circle(); circle.setCenterX(100);
circle.setCenterY(100); circle.setRadius(50); circle.setStroke(Color.BLACK);
circle.setFill(null);
 // Create a pane to hold the circle Pane pane = new Pane();
pane.getChildren().add(circle);
 // Create a scene and place it in the stage Scene scene = new Scene(pane, 200, 200);
 primaryStage.setTitle("ShowCircle"); // Set the stage title primaryStage.setScene(scene); // Place the sce
the stage primaryStage.show(); // Display the stage
 }
 public static void main(String[] args) { launch(args);}}

84
Ellipse

radiusX radiusY
(centerX, centerY)

85
Arc radiusY length

startAngle

0 degree

radiusX
(centerX, centerY)

86
Polygon and Polyline

The getter and setter methods for property values and a getter for property
javafx.scene.shape.Polygon itself are provided in the class, but omitted in the UML diagram for brevity.
+Polygon() Creates an empty polygon.
+Polygon(double... points) Creates a polygon with the given points.
+getPoints(): Returns a list of double values as x- and y-coordinates of the points.
ObservableList<Double
>

87
The Image and ImageView
Classes

88
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.layout.HBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.geometry.Insets;

public class ShowImage extends Application


{ @Override
public void start(Stage primaryStage) {
// Create a pane to hold the image views
Pane pane = new HBox(10);
pane.setPadding(new Insets(5, 5, 5, 5));
Image image = new Image("paul.jpg");
pane.getChildren().add(new ImageView(image));
ImageView imageView2 = new ImageView(image);
imageView2.setFitHeight(100);
imageView2.setFitWidth(100);
imageView2.setRotate(90);
pane.getChildren().add(imageView2);
Scene scene = new Scene(pane);
primaryStage.setTitle("ShowImage");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{ launch(args);
3 }
9 }

89
JavaFX CSS style and Node rotation
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.control.Button;
public class NodeStyleRotateDemo extends Application
{ @Override
public void start(Stage primaryStage)
{ StackPane pane = new StackPane();
Button btOK = new Button("OK");
btOK.setStyle("-fx-border-color: blue;");
pane.getChildren().add(btOK);
pane.setRotate(45);
pane.setStyle("-fx-border-color: red; -fx-background-color: lightgray;");
Scene scene = new Scene(pane, 200, 250);
primaryStage.setTitle("NodeStyleRotateDemo"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}

public static void main(String[] args)


{ launch(args);
}
}

90
JavaFX CSS style and Node rotation
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.control.Button;

public class NodeStyleRotateDemo extends Application


{ @Override
public void start(Stage primaryStage)
{ StackPane pane = new StackPane();

/* The StackPane layout pane places all of


the nodes within a single stack with each
new node added on top of the previous node.
This layout model provides an easy way to
overlay text on a shape or image and to
overlap common shapes to create a complex
shape. */

91
JavaFX External CSS style file
// Example to load and use a CSS style file in a scene import
javafx.application.Application;
import javafx.stage.Stage; import
javafx.scene.Scene;
import javafx.scene.layout.BorderPane;

public class ExternalCSSFile extends Application


{ @Override
public void start(Stage primaryStage) { try {
BorderPane root = new BorderPane(); Scene scene
= new Scene(root,400,400);
scene.getStylesheets().add(getClass()
.getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e)
{ e.printStackTrace();
}
}
public static void main(String[] args)
{ launch(args);
}
42 }

92
Thank You!

93

You might also like