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

Java chapter 3

Chapter Three covers GUI programming in Java, focusing on the Java GUI API hierarchy, simple GUI components, and layout managers such as FlowLayout, GridLayout, and BorderLayout. It explains the differences between AWT and Swing, highlighting Swing's advantages in terms of platform independence and component variety. The chapter also includes examples of creating GUI objects and using color and font classes.

Uploaded by

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

Java chapter 3

Chapter Three covers GUI programming in Java, focusing on the Java GUI API hierarchy, simple GUI components, and layout managers such as FlowLayout, GridLayout, and BorderLayout. It explains the differences between AWT and Swing, highlighting Swing's advantages in terms of platform independence and component variety. The chapter also includes examples of creating GUI objects and using color and font classes.

Uploaded by

mamomohi13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, 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:
3 ⚫ javax.swing.*,
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
Swing vs. AWT
Java AWT Java Swing
AWT components are platform- Java swing components are
dependent. platform-independent.
AWT components are Swing components are
heavyweight. lightweight.
AWT doesn't support pluggable Swing supports pluggable
look and feel. look and feel.
Swing provides more
AWT provides less components powerful components such
than Swing. as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.
AWT doesn't follows MVC(Model
View Controller) where model
represents data, view represents
Swing follows MVC.
presentation
6
and controller acts as
an interface between model and
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
8 to support GUI components.
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
JFrame
JFrameClass
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.
19
You can also place panels in a panel.
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
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).
•35 This is known as the RGB model.
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, Font.BOLD + Font.ITALIC (3)
Monospaced, 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);

JButton jbtOK = new JButton("OK");


37
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
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.
39 -border: javax.swing.border.Border The border for this component.
ImageIcon Class
• Image icons are objects created using the
ImageIcon class.
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 JSlider
JButton JTabbedPane
JCheckBox Jmenu
JRadioButton Jspinner
JScrollBar JColorChooser
JTextField JEditorPane
JPasswordField JTextPane
JTextArea JFileChooser
JComboBox JProgressBar
JTable JDialog
41
JTree
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.Stage is the top level JavaFX container (i.e.,
window)
• The primary Stage is constructed by the platform.
⚫ javafx.scene.Scene class is the container for all content
in a scene graph in the stage.
⚫ javafx.scene.Node is 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.Butto
n;

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

17

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) {
18 launch(args);
}}

68
BorderPane

19

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,
20 } 13.5, 14.5));
}

70
Hbox and VBox

21
(c) Paul Fodor and Pearson
Inc.

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);
Scene scene = new Scene(pane);
primaryStage.show();
} primaryStage.setScene(scene);

72
Display Shapes

⚫ Programming Coordinate Systems start from the left-


upper corner

23

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

24
(c) Paul Fodor and Pearson
Inc.

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();
}
26 .
} .
.

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();
32 }
...// 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 scen
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
javafx.scene.shape.Polygon property 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
ObservableList<Double> points.

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);
39 }
}

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