برمجة 3
برمجة 3
Handling Exceptions
• An exception is an object that is generated as
the result of an error or an unexpected event.
• Exception are said to have been “thrown.”
• It is the programmers responsibility to write
code that detects and handles exceptions.
• Unhandled exceptions will crash a program.
• Java allows you to create exception handlers.
int x = 10 , y = 0 ;
System.out.println (x/y);
Divide by Zero
Exception
• An exception is an error or a condition that prevents
execution of a program from proceeding normally.
• For example:
int[] x = {1, 5, 7}; int x = 5;
System.out.println(x[1]); int y = 0;
System.out.println(x[3]); int z = x/y;
System.out.println(x[0]); System.out.println(z);
System.out.println(x[2]); ArithmeticException
ArrayIndexOutOfBoundsException
Example
• import java.util.Scanner;
• public class Quotient {
• public static void main(String[] args) {
• Scanner input = new Scanner(System.in); // Prompt the user to
enter two integers
• System.out.print("Enter two integers: ");
• int number1 = input.nextInt();
• int number2 = input.nextInt();
• System.out.println(number1 + " / " + number2 + " is " +(number1 /
number2));
• }}
If you entered 0 for the second number, a runtime
error would occur, because you cannot divide an
integer by 0. (Note that a floating-point number
divided by 0 does not raise an exception.)
Exception Classes
The Throwable class is the root of exception classes. All Java
exception classes inherit directly or indirectly from Throwable.
You can create your own exception classes by extending
Exception or a subclass of Exception.
Exception Classes
• An exception handler is a section of code
that gracefully responds to exceptions.
• An exception is an object.
• Exception objects are created from classes in
the Java API hierarchy of exception classes.
• All of the exception classes in the hierarchy are
derived from the Throwable class.
• Error and Exception are derived from the
Throwable class. 11-7
Handling Exceptions
• To handle an exception, you use a try statement.
• try
• {
• (try block statements...)
• }
• catch (ExceptionType ParameterName)
• {
• (catch block statements...)
• }
• First the keyword try indicates a block of code will be
attempted. 11-8
Handling Exceptions
• After the try block, a catch clause appears.
• A catch clause begins with the key word
catch:
• catch (ExceptionType ParameterName)
– ExceptionType is the name of an exception class and
– ParameterName is a variable name which will reference the exception object if the code
in the try block throws an exception.
Exception Handling
• Exception handling enables a program to deal with
exceptional situations and continue its normal execution.
Try {
Statement or method that may throw an exception
}
Catch (type ex){
Code to process the exception
}
int[] x = {1, 5, 7}
Try {
System.out.println(x[3]);
} Catch (ArrayIndexOutOfBoundsException ex){
System.out.println(“You access an index out of bound”)
}
System.out.println(x[0]);
System.out.println(x[2]);
Handling Exceptions
• This code is designed to handle a FileNotFoundException if it
is thrown.
• try
• {
• File file = new File
("MyFile.txt"); Scanner
inputFile = new
Scanner(file);
• }
• catch (FileNotFoundException e)
• {
• System.out.println("File not found.");
• }
• The Java Virtual Machine searches for a catch clause that can deal 11-11
with the exception.
If user input
is char ‘a’?
Examples of Subclasses of Exception
name description Example
ClassNotFoundExce Attempt to use a class that does three class files, only two of
ption not exist. which could be found
IOException. Related to input/output Examples of subclasses of
operations, such as invalid input, IOException are
reading past the end of a file, and InterruptedIOException,
opening a nonexistent file EOFException and
FileNotFoundException
ArithmeticExceptio Dividing an integer by zero Note that floating-point
n arithmetic does not throw
exceptions
NullPointerExceptio Attempt to access an object
n through a null reference variable.
Exception Types
• RuntimeException and Error are known as unchecked
exceptions.
public class Test {
public static void main(String[] args) {
try {
• All other exceptions
FileReader are known as checkedFileNotFoundException
fr = new FileReader(“……”); exceptions.
}
catch (FileNotFoundException ex) {
• The compiler
} forces the programmer to check and deal
}
with
} the exceptions with type checked exceptions.
More on Exception Handling
Quiz-1
public class Test {
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
System.out.print(i + " ");
try {
System.out.println(1 / 0);
}
catch (Exception ex) {
System.out.println(“Error”);
}
}
}
}
Quiz-2
public class Main {
public static void main(String[] args) {
try {
for (int i = 0; i < 2; i++) {
System.out.print(i + " ");
System.out.println(1 / 0);
}
}
catch (Exception ex) {
System.out.println(“Error”);
}
}
}
ArithmeticException ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException ClassCastException
NullPointerException
Quiz 4
public class Main {
public static void main(String[] args) {
System.out.println(1.0 / 0);
}
catch (Exception ex) {
System.out.println(“Error”);
}
}
}
Infinity
Infinity
• 1/0 is a division of two ints, and throws an
exception because you can't divide by integer
zero.
• However, 0.0 is a literal of type double, and
Java will use a floating-point division.
• The IEEE floating-point specification has
special values for dividing by zero (among
other thing), one of these is double.
Quiz 5
public class Main {
public static void main(String[] args) {
System.out.println(1 / 0.0);
}
catch (Exception ex) {
System.out.println(“Error”);
}
}
}
Infinity
Quiz 6 (you)
• Point out the problem in the following code.
• Does the code throw any exceptions?
• System.out.println(value);
Quiz 7 (you)
• What is the output of the following code?
• public class Test {
• public static void main(String[] args) { try {
• int value = 30;
• if (value < 40)
• throw new Exception("value is too small");
• }
• catch (Exception ex) { System.out.println(ex.getMessage());
• }
• System.out.println("Continue after the catch block");
• }}
• What would be the output if the line int value = 30; were changed to
int value = 50;
Handling Multiple Exceptions
• The code in the try block may be capable of
throwing more than one type of exception.
• A catch clause needs to be written for each
type of exception that could potentially be
thrown.
• The JVM will run the first compatible catch
clause found.
• The catch clauses must be listed from most
specific to most general.
Exception Handlers
• There can be many polymorphic catch clauses.
• A try statement may have only one catch clause for each specific type of
exception.
• try
• {
• number = Integer.parseInt(str);
• }
• catch (NumberFormatException e)
• {
• System.out.println("Bad number format.");
• }
• catch (NumberFormatException e) // ERROR!!!
• {
• System.out.println(str + " is not a number.");
• }
Exception Handlers
• The NumberFormatException class is derived
from the
• IllegalArgumentException class.
• try
• {
• number = Integer.parseInt(str);
• }
• catch (IllegalArgumentException e)
• {
• System.out.println("Bad number format.");
• }
• catch (NumberFormatException e) // ERROR!!!
• {
• System.out.println(str + " is not a number.");
• }
Main.java:24: error: exception NumberFormatException has already been caught
catch(NumberFormatException e2)
Exception Handlers
• The previous code could be rewritten to work, as
follows, with no errors:
• try
• {
• number = Integer.parseInt(str);
• }
• catch (NumberFormatException e)
• {
• System.out.println(str + " is not a number.");
• }
• catch (IllegalArgumentException e) //OK
• {
• System.out.println("Bad number format.");
• }
Quiz 8
b
Throwing Exceptions
• You can write code that:
– throws one of the standard Java exceptions, or
– an instance of a custom exception class that you have designed.
try{
int x , y=10;
Scanner s= new Scanner(System.in);
x= s.nextInt ( );
if (x==0)
throw new IllegalArgumentException("Must be more than 0");
System.out.println(y/x); }
0
catch(ArithmeticException e){ wrong value
System.out.println("Error");} Final
catch(IllegalArgumentException e2)
{ System.out.println("wrong value");}
catch (InputMismatchException e3){
System.out.println("Enter only numeric value"); }
System.out.println("Final");
}
try{
int x , y=10;
Scanner s= new Scanner(System.in);
x= s.nextInt ( );
if (x==0)
throw new IllegalArgumentException("Must be more than 0");
System.out.println(y/x); }
catch(ArithmeticException e){
System.out.println("Error");}
catch (InputMismatchException e3){
System.out.println("Enter only numeric value"); }
System.out.println("Final");
} 0
Exception in thread "main" java.lang.IllegalArgumentException: Must
be more than 0 at Main.main(Main.java:17)
Declaring Exceptions
• Every method must state the types of checked exceptions
it might throw in method header.
• For example:
public void myMethod1() throws Exception1
public void myMethod2() throws Exception1, … , ExceptionN
public int getIndex(int index, int[] arr) {
int value = arr[index];
return value;
}
Catching Exceptions
• When an exception is thrown, it can be caught and
handled in a try-catch block.
public static int getIndex(int index, int[] arr) throws ArrayIndexOutOfBoundsException
{
if ( index >= arr.length){
throw new ArrayIndexOutOfBoundsException(“You access index out of bounds”);
} else{
int value = arr[index];
return value;
}
}
Quiz 9
Quiz 10
Finally Clause
• If no exception arises in the try block, finalStatements is
executed, and the next statement after the try statement is
executed.
• If a statement causes an exception in the try block that is
caught in a catch block, the rest of the statements in the try
block are skipped, the catch block is executed, and the finally
clause is executed. The next statement after the try statement
is executed.
• If one of the statements causes an exception that is not caught
in any catch block, the other statements in the try block are
skipped, the finally clause is executed, and the exception is
passed to the caller of this method.
Finally Clause
try { If no Exception
statement1
statement1; statement2
statement2; statement3
statement5
statement3; statement6
}
catch (Exception1 ex1) {
statement4;
} If caught Exception in statement2
statement1
finally { statement2
statement5; statement4
statement5
} statement6
statement6;
Quiz 11
Defining Custom Exception Classes
• You can define a custom exception class by extending the
java.lang.Exception class. Java provides quite a few
exception classes. Use them whenever possible instead of
defining your own exception classes. However, if you run into
a problem that cannot be adequately described by the
predefined exception classes, you can create your own
exception class, derived from Exception or from a subclass of
Exception, such as IOException.
Quiz 13
• public class Test {
• public static void main(String[] args) {
• try {
• for (int i = 0; i < 2; i++) { System.out.print(i + "
"); System.out.println(1 / 0);
• }
• }
• catch (Exception ex) {
• }
• }
• }
Quiz 14
• public class Test {
• public static void main(String[] args) {
• try {
• method();
• System.out.println("After the method call");
• }
• catch (ArithmeticException ex) {
System.out.println("ArithmeticException");
• }
• catch (RuntimeException ex) {
• System.out.println("RuntimeException");
• }
• catch (Exception e) {
• System.out.println("Exception");
• }
• }
• static void method() throws Exception {
• System.out.println(1 / 0);
• }
Quiz 15
• public class Test {
• public static void main(String[] args) {
• try {
• int[] list = new int[10];
• System.out.println("list[10] is " + list[10]); }
• catch (ArithmeticException ex) {
• System.out.println("ArithmeticException");
• }
• catch (RuntimeException ex) {
• System.out.println("RuntimeException");
• }
• catch (Exception ex) {
• System.out.println("Exception"); } }}
THANKS
for your attention
Programming -3
3 Year – first Semester
Lecture 3: Text I/O & Binary I/O
Previous lecture
class Main {
public static void main(String args[]) {
int[] arr = {3, 5, 7};
try {
int x = getIndex(4,arr);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println(ex.getMessage());
}
}
Class Example {
public static void main (String args[]) {
int[] arr = {3, 5, 7};
int x = getIndex(4, arr);
}
public static int getIndex(int index, int[] arr) {
int value;
try{
value = arr[index];
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println(ex.getMessage());
}
return value;
}
}
ArithmeticException ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException ClassCastException
NullPointerException
File Class
File Class
• Files are used to store data created in the program
permanently.
• File Class contains the methods for:
– obtaining the properties of a file/directory
– renaming and deleting a file/directory. Directory
– Creating directory.
• Creating File object: FileName.Extension
Relative file name
import java.io.File;
File f = new File(“D:/Programs/test.txt”);
– OR Absolute file name
+File(pathname: String)
Method Return value File Directory
+listFile() File[] No Yes
+delete() boolean Yes Yes
+renameTo(dest: File) boolean Yes Yes
+mkdir() boolean No Yes
+mkdirs() boolean No Yes
Note:
import java.io.File;
……
File f1 = new File(“D:/test.txt”);
File f2 = new File(“src/test.txt”);
File f3 = new File(“test.txt”);
File Class This class contains the methods for obtaining the
properties of a file/directory and for renaming and
deleting a file/directory.
Absolute File name that contains the full path and file name
file name Ex: C:\book\WelcomeJava
directory The path to the directory a file is housed.
path Ex: C:\book\
relative file is in relation to the current working directory
name Ex: WelcomeJava
Quiz 1
• What is wrong about creating a File object using the
following statement?
new File("c:\book\test.dat");
new File("c:\\book\\test.dat");
new File("c:/book/test.dat");
• Can you use the File class for I/O?
NO, The File class can be used to obtain file properties and
manipulate files, but cannot perform I/O.
• Does creating a File object create a file on the disk?
NO , Creating a File object does not create a
file/directory on the disk.
Note
• The \ is a special character. It should be written as \\ in Java using
the Escape sequence.
• How do you check whether a file already exists?
Use exists() in the File class to check whether a file exists.
• How do you delete a file?
Use delete() in the File class to delete this file.
• How do you rename a file?
Use renameTo(File) to rename the name for this file.
• Can you find the file size (the number of bytes) using the File class?
Use length() to return the file size
How do you create a directory?
Use mkdir or mkdirs to create a directory under this File object.
Text I/O
Text I/O
• In order to write data to text files, we use PrintWriter
class.
• In order to read data from text files, we use Scanner
class.
• The objects from these classes contain the methods for
reading/writing data from/to a file.
• To read a file, create a File object and pass it as a
parameter when constructing a Scanner.
• File f = new File("numbers.txt");
Scanner input = new Scanner(f);
PrintWriter Class
• The java.io.PrintWriter class can be used to create a
file and write data to a text file.
• First, you have to import class
import java.io.PrintWriter;
• Then create a PrintWriter object for a text file as
follows:
PrintWriter output = new PrintWriter(filename/fileobject);
If file doesn’t exist, it will be created
+PrintWriter(file: File)
+PrintWriter(filename: String)
Method Return value
+println(d: double) void
+println(b: boolean) void
+printf(format, argument) void
• }}
Note
• You have used the System.out.print,
System.out.println, and System.out. printf
methods to write text to the console. System.out
is a standard Java object for the console output.
You can create PrintWriter objects for writing text
to any file using print, println, and printf
• The close() method must be used to close the file
If this method is not invoked, the data may not be
saved properly in the file.
try-with-resources Example
import java.io.File;
import java.io.PrintWriter;
public class Test {
public static void main(String[] args) throws FileNotFoundException{
File f = new File("D:/New/Java/test.txt");
try (PrintWriter pw = new PrintWriter(f)) {
pw.print("Welcome to java");
pw.println();
pw.println(120);
pw.println(17.05);
pw.printf("we are going to %s", "Cinema");
}
}
}
Quiz 2
• How do you create a PrintWriter to write data
to a file?
use new PrintWriter(filename).
• What is the reason to declare throws
Exception in the main method?
Java forces you to write the code to deal with
exceptions. One way to deal with it is to declare
throws Exception in the method declaration
• What would happen if the close() method
were not invoked?
the data may not be saved properly.
Scanner Class
• The java.util.Scanner class is used to read strings and
primitive values from the console
• A Scanner breaks its input into tokens delimited by
whitespace characters. To read from the keyboard, you
create a Scanner for System.in, as follows:
Scanner input = new Scanner(System.in);
• To read from a file, create a Scanner for a file, as
follows:
Scanner input = new Scanner(new File(filepath));
Scanner Class Example 1
• import java.util.*;
• import java.io.PrintWriter;
• import java.io.File;
• import java.io.*; // for I/O
• public class Main {
• public static void main(String[] args) {
• File f = new File("E:/test.txt");
• try (Scanner s = new Scanner(f)){
• while (s.hasNext()) {
• String Name = s.next();
• int ID = s.nextInt();
• double GPA = s.nextDouble();
• String dept = s.next();
• System.out.println("My name is " + Name + " " + " and ID " + ID + " in department " + dept);
• }
• } catch (FileNotFoundException ex) {
• ex.printStackTrace();
• }
• }
• }
Scanner Class Example 2
File f = new File("D:/New/Java/test.txt");
try (Scanner s = new Scanner(f)){
while (s.hasNext()) {
String fName = s.next();
String lName = s.next();
int age = s.nextInt();
String dept = s.next();
System.out.println("My name is " + fName + " " + lName
+ " with age " + age + " in department " + dept);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
Output:
My name is Mohamed Mostafa with age 21 in department CS
My name is Aya Said with age 22 in department IS
Quiz 4
• What will happen if you attempt to create a
Scanner for a nonexistent file?
– an exception will occur
• What will happen if you attempt to create
a PrintWriter for an existing file?
– the contents of the existing file will be gone.
• Suppose you enter 45 57.8 789, then press the Enter key. Show
the contents of the variables after the following code is
executed.
Scanner input = new Scanner(System.in);
45 int intValue = input.nextInt();
57.8 double doubleValue = input.nextDouble();
789 String line = input.nextLine();
• Suppose you enter 45, press the Enter key, 57.8, press the
Enter key, 789, and press the Enter key. Show the contents of
the variables after the following code is executed.
Scanner input = new Scanner(System.in);
45 int intValue = input.nextInt();
57.8 double doubleValue = input.nextDouble();
null String line = input.nextLine();
Task
• Write a program that reads the first 5 values
from this file and prints them along with their
sum. Its output:
number = 308.2
number = 14.9
number = 7.4
number = 2.8
number = 3.9
Sum = 337.19999999999993
• import java.util.*;
import java.io.File;
import java.io.*; // for I/O
public class Main {
public static void main(String[] args) throws
FileNotFoundException {
Scanner input = new Scanner(new
File("E:/numbers.txt"));
double sum = 0.0;
while (input.hasNextDouble()) {
double next = input.nextDouble();
System.out.println("number = " + next);
sum += next;
}
System.out.println("Sum = " + sum);;
}}
Reading data from web
• For an application program to read data from a URL, you first
need to create a URL object using the java.net.URL class with
this constructor:
public URL(String spec) throws MalformedURLException
• For example, the following statement creates a URL object for
http://www.google.com/index.html.
try {
URL url = new URL("http://www.google.com/index.html");
}
catch (MalformedURLException ex) {
ex.printStackTrace();
}
• A MalformedURLException is thrown if the URL string has a
syntax error.
Binary I/O
• Files can be classified as either text or binary.
• A file that can be processed (read, created, or modified)
using a text editor such as Notepad on Windows is
called a text file.
• All the other files are called binary files. You cannot read
binary files using a text editor—they are designed to be
read by programs.
• For example, Java source programs are text files and
can be read by a text editor, but Java class files are
binary files and are read by the JVM.
• Java offers many classes for performing file input and
output. These can be categorized as text I/O classes and
binary I/O classes
• Text data are read using the Scanner class
and written using the PrintWriter class.
Quiz 5
• What is a text file and what is a binary file?
– Although it is not technically precise, a text file
consists of a sequence of characters and a
binary file consists of a sequence of bits.
• Can you view a text file or a binary file
using a text editor?
– You can use a text editor to view a text file,
but not a binary file.
Quiz 6
• What are the differences between text I/O
and binary I/O?
– Binary I/O reads a byte from a file and copies
it directly to the memory without any
conversion, vice versa. Text I/O requires
encoding and decoding.
Quiz 7
• If you write the string "100" to an ASCII
text file, what values are stored in the file?
– the values stored are 0x31 0x30 0x30.
• If you write a numeric byte-type value 100
using binary I/O, what values are stored in
the file?
– he value stored in the file is 0x64.
Binary I/O Classes
Thank You
Programming -3
3 Year – first Semester
Lecture 4: Strings, Characters and Regular
Expressions
OBJECTIVES
2
3
Introduction
• Characters
– “Building blocks” of Java source programs
– Character literals ‘a’ ‘2’ ‘+’
– Unicode character set ( 2 byte ) – international
• String
– Series of characters treated as single unit
– May include letters, digits, special characters.
– Object of class String
– String literals “12345” “” “Hello”
4
Performance Tip
String Constructors
• No-argument constructor
• Creates a String object containing an empty String
• One-argument constructor
• A String object
• One-argument constructor
• A char array
• Three-argument constructor
• A char array
• An integer specifies the starting position
• An integer specifies the number of characters to access
7
Note
•class String does not provide any methods that allow the contents
of a String object to be modified.
8
9
StringIndexOutOfBoundsException.
10
String Methods
length, charAt and getChars
• Method length()
• Determine the length of a String
• Like arrays, Strings always “know” their size
• Unlike arrays, Strings do not have a length instance variable
• Method charAt()
• Get character at specific location in String
• Method getChars()
• Get entire set of characters in String
• The first argument is the starting index in the String from which
characters are to be copied.
• The second argument is the index that is one past the last character
to be copied from the String.
• The third argument is the character array into which the characters
are to be copied.
• The last argument is the starting index where the copied characters
are placed in the target character array.
12
Copy (some of) s1’s
characters to charArray
13
14
Comparing Strings
• Strings are compared using the numeric codes of the characters in the
strings.
• Comparing String objects
• Method equals
• Method equalsIgnoreCase
• Method compareTo
• Method regionMatches
15
16
17
Comparing Strings
• Method equals tests any two objects for equality
• The method returns true if the contents of the objects are equal, and false
otherwise.
• Uses a lexicographical comparison.
• When primitive-type values are compared with ==, the
• result is true if both values are identical.
• When references are compared with ==, the result is true
• if both references refer to the same object in memory.
• Java treats all string literal objects with the same contents as
• one String object to which there can be many references.
19
•When two identical (but separate) objects are compared with ==, the
result will be false. When comparing objects to determine whether
they have the same contents, use method equals.
Comparing Strings
22
23
24
25
26
28
Concatenating Strings
• Method concat
• Concatenate two String objects
30
32
33
Class StringBuilder
• Class StringBuilder
34
Performance Tip
Performance Tip
36
• One-argument constructor
• int argument
• Specifies the initial capacity
• One-argument constructor
• String argument
• Creates StringBuilder containing the characters in the String argument
1 // Fig. 30.10: StringBuilderConstructors.java
2 // StringBuilder constructors.
3
4 public class StringBuilderConstructors
5 {
6 public static void main( String args[] )
7 {
8 StringBuilder buffer1 = new StringBuilder();
9 StringBuilder buffer2 = new StringBuilder( 10 );
10 StringBuilder buffer3 = new StringBuilder( "hello" );
11
12 System.out.printf( "buffer1 = \"%s\"\n", buffer1.toString() );
13 System.out.printf( "buffer2 = \"%s\"\n", buffer2.toString() );
14 System.out.printf( "buffer3 = \"%s\"\n", buffer3.toString() );
15 } // end main
16 } // end class StringBuilderConstructors
buffer1 = ""
buffer2 = ""
buffer3 = "hello"
37
38
• Method length()
• Return StringBuilder length
• Method capacity()
• Return StringBuilder capacity
• Method setLength()
• Increase or decrease StringBuilder length
• Method ensureCapacity()
• Set StringBuilder capacity
• Guarantee that StringBuilder has minimum capacity
1 // Fig. 30.11: StringBuilderCapLen.java
2 // StringBuilder length, setLength, capacity and ensureCapacity methods.
3
4 public class StringBuilderCapLen
5 {
6 public static void main( String args[] )
7 {
8 StringBuilder buffer = new StringBuilder( "Hello, how are you?" );
9
10 System.out.printf( "buffer = %s\nlength = %d\ncapacity = %d\n\n",
11 buffer.toString(), buffer.length(), buffer.capacity() );
12
13 buffer.ensureCapacity( 75 );
14 System.out.printf( "New capacity = %d\n\n", buffer.capacity() );
15
16 buffer.setLength( 10 );
17 System.out.printf( "New length = %d\nbuf = %s\n",
18 buffer.length(), buffer.toString() );
19 } // end main
20 } // end class StringBuilderCapLen
New capacity = 75
New length = 10
buf = Hello, how
39
40
StringBuilder Methods
• Method setCharAt()
• Set StringBuffer character at specified index
• Method getChars()
• Return character array from StringBuffer
• Method reverse()
• Reverse StringBuffer contents
• Method append()
• Allow data values to be added to StringBuilder
1 // Fig. 30.12: StringBuilderChars.java
2 // StringBuilder methods charAt, setCharAt, getChars and reverse.
3
4 public class StringBuilderChars
5 {
6 public static void main( String args[] )
7 {
8 StringBuilder buffer = new StringBuilder( "hello there" );
9
10 System.out.printf( "buffer = %s\n", buffer.toString() );
11 System.out.printf( "Character at 0: %s\nCharacter at 4: %s\n\n",
12 buffer.charAt( 0 ), buffer.charAt( 4 ) );
13
14 char charArray[] = new char[ buffer.length() ];
15 buffer.getChars( 0, buffer.length(), charArray, 0 );
16 System.out.print( "The characters are: " );
17
18 for ( char character : charArray )
19 System.out.print( character );
20
41
21 buffer.setCharAt( 0, 'H' );
22 buffer.setCharAt( 6, 'T' );
23 System.out.printf( "\n\nbuf = %s", buffer.toString() );
24
25 buffer.reverse();
26 System.out.printf( "\n\nbuf = %s\n", buffer.toString() );
27 } // end main
28 } // end class StringBufferChars
42
43
44
21 buffer.append( objectRef );
22 buffer.append( "\n" ); // each of these contains new line
23 buffer.append( string );
24 buffer.append( "\n" );
25 buffer.append( charArray );
26 buffer.append( "\n" );
27 buffer.append( charArray, 0, 3 );
28 buffer.append( "\n" );
29 buffer.append( booleanValue );
30 buffer.append( "\n" );
31 buffer.append( characterValue );
32 buffer.append( "\n" );
33 buffer.append( integerValue );
34 buffer.append( "\n" );
35 buffer.append( longValue );
36 buffer.append( "\n" );
37 buffer.append( floatValue );
38 buffer.append( "\n" );
39 buffer.append( doubleValue );
40 buffer.append( "\n" );
41 buffer.append( lastBuffer );
42
45
buffer contains
hello
goodbye
abcdef
abc
true
Z
7
10000000000
2.5
33.333
last StringBuilder
46
47
StringBuilder
Insertion and Deletion Methods
• Method insert()
• Allow data-type values to be inserted into StringBuilder
40 System.out.printf(
41 "buffer after inserts:\n%s\n\n", buffer.toString() );
42
43 buffer.deleteCharAt( 10 ); // delete 5 in 2.5
44 buffer.delete( 2, 6 ); // delete .333 in 33.333
45
46 System.out.printf(
47 "buffer after deletes:\n%s\n", buffer.toString() );
48 } // end main
49 } // end class StringBuilderInsert
50
51
Class Character
• Treat primitive variables as objects
52
14 // display character info
15 System.out.printf( "is defined: %b\n", Character.isDefined( c ) );
16 System.out.printf( "is digit: %b\n", Character.isDigit( c ) );
17 System.out.printf( "is first character in a Java identifier: %b\n",
18 Character.isJavaIdentifierStart( c ) );
19 System.out.printf( "is part of a Java identifier: %b\n",
20 Character.isJavaIdentifierPart( c ) );
21 System.out.printf( "is letter: %b\n", Character.isLetter( c ) );
22 System.out.printf(
23 "is letter or digit: %b\n", Character.isLetterOrDigit( c ) );
24 System.out.printf(
25 "is lower case: %b\n", Character.isLowerCase( c ) );
26 System.out.printf(
27 "is upper case: %b\n", Character.isUpperCase( c ) );
28 System.out.printf(
29 "to upper case: %s\n", Character.toUpperCase( c ) );
30 System.out.printf(
31 "to lower case: %s\n", Character.toLowerCase( c ) );
32 } // end main
33 } // end class StaticCharMethods
53
Class StringTokenizer
• Tokenizer
• Partition String into individual substrings
• Use delimiter to separate strings
• Typically whitespace characters (space, tab, newline, etc)
• Java offers java.util.StringTokenizer
56
1 // Fig. 30.18: TokenTest.java
2 // StringTokenizer class.
3 import java.util.Scanner;
4 import java.util.StringTokenizer;
5
6 public class TokenTest
7 {
8 // execute application
9 public static void main( String args[] )
10 {
11 // get sentence
12 Scanner scanner = new Scanner( System.in );
13 System.out.println( "Enter a sentence and press Enter" );
14 String sentence = scanner.nextLine(); Use StringTokenizer to parse String using
15 default delimiter “ \n\t\r”
16 // process user sentence
17 StringTokenizer tokens = new StringTokenizer( sentence );
18 System.out.printf( "Number of elements: %d\nThe tokens are:\n",
19 tokens.countTokens() );
20
21 while ( tokens.hasMoreTokens() ) Display next token as long
22 System.out.println( tokens.nextToken() ); as tokens exist
23 } // end main
24 } // end class TokenTest
Enter a sentence and press Enter
This is a sentence with seven tokens
Number of elements: 7
The tokens are:
This
is
a
sentence
with
seven
tokens
57
Regular Expressions
• Regular expression
• Sequence of characters and symbols
• Useful for validating input and ensuring data format
• E.g., ZIP code
• Facilitate the construction of a compiler
58
Regular Expressions
• Digit
• Numeric character
• Word character
• Any letter, digit, underscore
• Whitespace character
• Space, tab, carriage return, newline, form feed
59
60
Regular Expressions
• Other patterns
• Square brackets ([])
• Match characters that do not have a predefined character class
• E.g., [aeiou] matches a single character that is a vowel
• Dash (-)
• Ranges of characters
• E.g., [A-Z] matches a single uppercase letter
• ^
• Don’t include the indicated characters
• E.g., [^Z] matches any character other than Z
61
Regular Expressions
• Quantifiers
• Plus (+)
• Match one or more occurrences
• E.g., A+
• Matches AAA but not empty string
• Asterisk (*)
• Match zero or more occurrences
• E.g., A*
• Matches both AAA and empty string
• Others in Fig. 22
62
• Quantifier Matches
Quiz
1.Create a regular expression that accepts 10 digit numeric chara
cters starting with 7, 8 or 9 only.
• Pattern.matches("[789][0-9]{9}", "9953038949")
• Write a regular expression that will match any mobile phone
numbers provided by the three main mobile networks
(Vodafone, 2degrees and Spark) in New Zealand. Vodafone
has the prefix 021 followed by 6 to 8 digits. 2degrees has the
prefix 022 followed by 7 digits. Spark has the prefix 027
followed by 7 digits
1 // Fig. 30.20: ValidateInput.java
2 // Validate user information using regular expressions.
3
4 public class ValidateInput
5 {
6 // validate first name
7 public static boolean validateFirstName( String firstName )
8 {
9 return firstName.matches( "[A-Z][a-zA-Z]*" );
10 } // end method validateFirstName
11
12 // validate last name
13 public static boolean validateLastName( String lastName )
14 {
15 return lastName.matches( "[a-zA-z]+([ '-][a-zA-Z]+)*" );
16 } // end method validateLastName
17 Method matches
18 // validate address returns true if the
19 public static boolean validateAddress( String address )
String matches
20 {
21 return address.matches(
the regular
22 "\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" ); expression
23 } // end method validateAddress
24
25 // validate city
26 public static boolean validateCity( String city )
27 {
28 return city.matches( "([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" );
29 } // end method validateCity
30
65
31 // validate state
32 public static boolean validateState( String state )
33 {
34 return state.matches( "([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" ) ;
35 } // end method validateState
36
37 // validate zip Method
38 public static boolean validateZip( String zip ) matches returns
true if the
39 {
String matches
40 return zip.matches( "\\d{5}" ); the regular
41 } // end method validateZip expression
42
43 // validate phone
44 public static boolean validatePhone( String phone )
45 {
46 return phone.matches( "[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}" );
47 } // end method validatePhone
48 } // end class ValidateInput
66
1 // Fig. 30.21: Validate.java
2 // Validate user information using regular expressions.
3 import java.util.Scanner;
4
5 public class Validate
6 {
7 public static void main( String[] args )
8 {
9 // get user input
10 Scanner scanner = new Scanner( System.in );
11 System.out.println( "Please enter first name:" );
12 String firstName = scanner.nextLine();
13 System.out.println( "Please enter last name:" );
14 String lastName = scanner.nextLine();
15 System.out.println( "Please enter address:" );
16 String address = scanner.nextLine();
17 System.out.println( "Please enter city:" );
18 String city = scanner.nextLine();
19 System.out.println( "Please enter state:" );
20 String state = scanner.nextLine();
21 System.out.println( "Please enter zip:" );
22 String zip = scanner.nextLine();
23 System.out.println( "Please enter phone:" );
24 String phone = scanner.nextLine();
25
67
68
69
Please enter first name:
Jane
Please enter last name:
Doe
Please enter address:
123 Some Street
Please enter city:
Some City
Please enter state:
SS
Please enter zip:
123
Please enter phone: Indicate that the entry
123-456-7890
for “zip” was invalid
Validate Result:
Invalid zip code
Validate Result:
Valid input. Thank you.
70
Regular Expressions
• Class Pattern
• Represents a regular expression
• Class Matcher
• Contains a regular-expression pattern and a CharSequence
• Interface CharSequence
• Allows read access to a sequence of characters
• String and StringBuilder implement CharSequence
1 // Fig. 30.24: RegexMatches.java 71
2 // Demonstrating Classes Pattern and Matcher.
3 import java.util.regex.Matcher;
4 import java.util.regex.Pattern;
5
6 public class RegexMatches
7 {
8 public static void main( String args[] )
9 {
10 // create regular expression
11 Pattern expression =
12 Pattern.compile( "J.*\\d[0-35-9]-\\d\\d-\\d\\d" );
13
14 String string1 = "Jane's Birthday is 05-12-75\n" +
15 "Dave's Birthday is 11-04-68\n" +
16 "John's Birthday is 04-28-73\n" +
17 "Joe's Birthday is 12-17-77";
18
19 // match regular expression to string and print matches
20 Matcher matcher = expression.matcher( string1 );
21
22 while ( matcher.find() )
23 System.out.println( matcher.group() );
24 } // end main
25 } // end class RegexMatches
Agenda
• JAVAFX VS SWING AND AWT
• Structure of a JavaFX Program
• Panes, UI Controls, and Shapes
• Property Binding
• Common Properties and Methods for Nodes
• The Color Class
• The Font Class
• The Image and ImageView Classes
JavaFX vs Swing and AWT
When Java was introduced, the GUI classes were
bundled in a library known as the Abstract
Windows Toolkit (AWT).
2
10:35
✦ Application
Stage
Scene
Button
3
10:35
Example 1
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
public class Example1 extends Application {
@Override
public void start(Stage primaryStage) {
Button b1 = new Button("OK");
Scene s1 = new Scene(b1, 200, 200);
primaryStage.setScene(s1);
primaryStage.setTitle("Example 1");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Structure of a JavaFX Program
• Notes:
– The launch method is a static method defined in the Application class for
launching a stand-alone JavaFX application.
– The main method is not needed if you run the program from the command
line, JVM automatically invokes the launch method to run the application.
– The class overrides the start method defined in
javafx.application.Application.
– The start method normally places UI controls in a scene and displays the
scene in a stage.
– A Stage object called primaryStage is automatically created by the JVM
when the application is launched.
Notes on MyJavaFX.java
✦ The main class overrides the start method defined in
javafx.application.Application
✦ After a JavaFX application is launched:-
– the JVM constructs an instance of the class using its no-arg
constructor and
– invokes its start method.
✦ The start method normally places UI controls in a scene and
displays the scene in a stage
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.setTitle("MyJavaFX"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stag, ,stage dimensions will adapt to scene
primaryStage.show(); // Display the stage
}
1
10:35
Stage-Scene
✦ A Stage object is a window.
✦ A Stage object called primary stage is
automatically created by the
JVM application islaunched
✦ You can create additional stages if needed
✦ Class Button is subclass of class Parent
javafx.stage.Stage
public final void setScene(Scene value)
Specify the scene to be used on thisstage.
Stage ( )
Creates a new instance of decorated Stage.
javafx.scene.Scene
Scene(Parent root, double width, double height)
Creates a Scene for a specific root Node with a specific size.
10:35
Example:Multiple Stages
Quiz 2
• What is the output of the following code?
import javafx.application.Application;
import javafx.stage.Stage;
public class Test extends Application {
public Test() {
System.out.println("Test constructor is invoked"); 2
}
launch application
@Override Test constructor is invoked
public void start(Stage primaryStage) { start method is invoked
System.out.println("start method is invoked"); 3
}
public static void main(String[] args) {
System.out.println("launch application"); 1
Application.launch(args);
}
}
Panes, UI Controls, and Shapes
✦ When you run MyJavaFX, The button is always centered in
the scene and occupies the entire window no matter how
you resize it.
✦ You can fix the problem by setting the position and size
properties of a button.
– a better approach is to use container classes, called panes, for
automatically laying out the nodes in a desired location and size.
– You place nodes inside a pane and then place the pane into a
scene.
1
10:35
5
1
10:35
Panes, UI Controls, and Shapes
• Stage can have only one Scene but will own solely its reference
• Scene can have only one Parent but will own solely its reference
• Pane can have many nodes, but will own solely each reference of them 11
10:3
5
1
10:35
javafx.scene.layout.Pane
public class Pane extends Region
This class may be used directly in cases where absolute positioning of children is
required since it does not perform layout beyond resizing resizable children to
their preferred sizes.
It is the application's responsibility to position the children since the pane leaves
the positions alone during layout
javafx.scene.layout.Pane
Pane( )
Creates a Pane layout
protected ObservableList<Node> getChildren()
Gets the list of children of this Parent.
javafx.collections. ObservableList<E>
boolean add(E e)
Appends the specified element to the end of this list
1
10:35
9
javafx.scene.layout.StackPane
javafx.scene.layout.StackPane
StackPane( )
Creates a StackPane layout with default CENTERalignment.
protected ObservableList<Node> getChildren()
Gets the list of children of this Parent.
Example 3
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.Scene;
public class Example3 extends Application {
@Override
public void start(Stage primaryStage) {
Button b1 = new Button("OK");
StackPane stackPane = new StackPane();
stackPane.getChildren().add(b1);
Scene s1 = new Scene(stackPane, 200, 200);
primaryStage.setTitle("Button in StackPane");
primaryStage.setScene(s1);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Example:using StackPane
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
2
10:35
3
Display a Shape
This example displays a circle in the center of the pane.
Y Axis
(0, 0) X Axis
y
(x, y)
(0, 0) X Axis
Java Conventional
Coordinate Coordinate
System
Y Axis System
Example 4
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
public class Example4 extends Application {
@Override
public void start(Stage primaryStage) {
Circle c = new Circle();
c.setCenterX(100);
c.setCenterY(100);
c.setRadius(50);
c.setStroke(Color.BLACK);
c.setFill(Color.BLUEVIOLET);
Pane pane = new Pane();
pane.getChildren().add(c);
Scene s1 = new Scene(pane, 200, 200);
primaryStage.setTitle("Show Circle");
primaryStage.setScene(s1);
primaryStage.show();
primaryStage.setResizable(false);
}
}
Quiz 3
• Can you prevent the user from resizing the stage?
Yes using stageObject.setResizable(false);
• How do you create a Scene object?
Scene s = new Scene(node);
Scene s = new Scene(node, Width, Height);
• How do you set a scene in a stage?
stageObject.setScene(sceneObject);
• How do you place a circle into a scene?
By adding circle to pane and then add pane to scene
Quiz 4
• Can you directly place a Shape or an ImageView into a
Scene?
NO
• Can you directly place a Control or a Pane into a Scene?
YES
• How do you create a Circle object?
Circle c = new Circle();
• How do you set Circle stroke color and fill color?
circleObject.setStroke(color);
circleObject.setFill(color);
Property Binding
• JavaFX introduces a new concept called property
binding that enables a target object to be bound to a
source object.
• If the value in the source object changes, then the target
object is also changed automatically.
• The target object is called a binding object or a binding
property and the source object is called a bindable object
or observable object.
Example 5
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
public class Example5 extends Application {
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
Circle c = new Circle();
c.setCenterX(100); c.centerXProperty.bind((pane.widthPropery.divide(2));
c.setCenterY(100); c.centerYProperty.bind((pane.heightPropery.divide(2));
c.setRadius(50);
c.setStroke(Color.BLACK);
c.setFill(Color.BLUEVIOLET);
pane.getChildren().add(c);
Scene s1 = new Scene(pane, 200, 200);
primaryStage.setTitle("Show Circle");
primaryStage.setScene(s1);
primaryStage.show();
}
}
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
c.setRadius(50);
c.setStroke(Color.BLACK);
c.setFill(Color.BLUEVIOLET);
pane.getChildren().add(c);
Scene s1 = new Scene(pane, 200, 200);
primaryStage.setTitle("Show Circle");
primaryStage.setScene(s1);
primaryStage.show();
// Display the stage
}
public static void main(String[] args) {
launch(args);
}
}
Property Binding
• JavaFX defines binding properties for primitive types and
strings (e.g., DoubleProperty, FloatProperty,
IntegerProperty, and StringProperty).
• These properties are subtypes of ObservableValue. So
they can also be used as source objects for binding
properties.
• By convention, each binding property has a getter and
setter method for returning and setting the property’s
value. It also has a getter method for returning the
property itself.
• This is called unidirectional binding.
Example 6
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.stage.Stage;
3
10:35
• -fx-border-color:red -fx-stroke: red;
• -fx-background-color:green -fx-fill:
green;
Example 7
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class JavaFXApplication2 extends Application {
@Override
public void start(Stage primaryStage) {
StackPane pane = new StackPane();
Button b = new Button("Computer");
b.setStyle("-fx-border-color:blue;");
b.setRotate(30);
pane.setStyle("-fx-border-color:red;-fx-background-color:green");
pane.getChildren().add(b);
Scene s1 = new Scene(pane, 200, 200);
primaryStage.setTitle("Test Style and Rotate");
primaryStage.setScene(s1);
primaryStage.show();
}
}
Quiz 5
• How do you set a style of a node with border color red?
nodeObject.setStyle("-fx-border-color:red;”);
• Write code to set the text color for the button to red?
buttonObject.setStyle("-fx-text-fill:red;”);
• Can you rotate a pane or a button?
objectName.setRotate(value);
• Modify the code to rotate the button 15 degrees
counterclockwise?
buttonObject.setRotate(-15);
Color Class
• The Color class can be used to create colors.
• JavaFX defines the abstract Paint class for painting a
node. The javafx.scene.paint.Color is a concrete
subclass of Paint, which is used to encapsulate colors.
-red: double
-green: double
-blue: double
-opacity: double
+Color(r: double, g: double, b:double, opacity: double)
+brighter(): Color
+darker(): Color
+color(r: double, g: double, b:double): Color
+color(r: double, g: double, b:double, opacity: double): Color
+rgb(r: int, g: int, b: int):Color
+rgb(r: int, g: int, b: int, opacity: double): Color
Color Class
• This is known as the RGBA model, where RGBA
stands for red, green, blue, and alpha. The alpha value
indicates the opacity.
• The Color class is immutable. Once a Color object is
created, its properties cannot be changed. The
brighter() method returns a new Color with a larger
red, green, and blue values and the darker() method
returns a new Color with a smaller red, green, and blue
values. The opacity value is the same as in the original
Color object.
Color Class
• You can also create a Color object using the static
methods color(r, g, b), color(r, g, b, opacity), rgb(r, g,
b), and rgb(r, g, b, opacity).
• Alternatively, you can use one of the many standard
colors such as BEIGE, BLACK, BLUE, BROWN,
CYAN, DARKGRAY, GOLD, GRAY, GREEN,
LIGHTGRAY, MAGENTA, NAVY, ORANGE, PINK,
RED, SILVER, WHITE, and YELLOW defined as
constants in the Color class.
Quiz 6
• Give for ways to fill a circle with red color?
circleObject.setFill(Color.RED);
circleObject.setFill(Color.color(1.0, 0 , 0));
circleObject.setFill(Color.rgb(255, 0 , 0));
Font Class
• A Font describes font name, weight, and size for
rendering text. javafx.scene.text.Font class is used to
create fonts.
-size: double
-name: String
-family: String
+Font(size: double)
+Font(name: String, size:double)
+font(name: String, size:double)
+font(name: String, w:FontWeight, size: double)
+font(name: String, w: FontWeight, p: FontPosture, size:double)
+getFamilies(): List<String>
+getFontNames(): List<String>
Font Class
• A Font instance can be constructed using its
constructors or using its static methods.
• A Font is defined by its name, weight, posture, and
size.
– Times, Courier, and Arial are the examples of the font
names. You can obtain a list of available font family names
by invoking the static getFamilies() method.
– The font weight are constants such as: FontWeight.LIGHT ,
FontWeight.NORMAL, and FontWeight.BOLD.
– The font postures are two constants: FontPosture.ITALIC
and FontPosture.REGULAR.
4
10:35
Example 8
public void start(Stage primaryStage) {
Pane pane = new StackPane();
Circle circle = new Circle();
circle.setRadius(50);
circle.setStroke(Color.BLACK);
circle.setFill(new Color(0.7, 0.2, 0.5, 0.8));
pane.getChildren().add(circle);
Label label = new Label(“Computer Language");
label.setFont(Font.font("Times New Roman", FontWeight.BOLD,
FontPosture.ITALIC, 20));
pane.getChildren().add(label);
Scene scene = new Scene(pane);
primaryStage.setTitle(“Example 8");
primaryStage.setScene(scene);
primaryStage.show();
}
4
10:35 8
The ImageView Class
10:35 49
+Image(filenameOrURL: String)
javafx.scene.image.ImageView
-fitHeight: DoubleProperty
-fitWidth: DoubleProperty
-x: DoubleProperty
-y: DoubleProperty
-image: ObjectProperty<Image>
+ImageView()
+ImageView(image: Image)
+ImageView(filenameOrURL: String)
Example 2
public void start(Stage primaryStage){
Image image = new Image("egy.jpg");
ImageView imageView = new ImageView(image);
imageView.setFitWidth(200);
imageView.setFitHeight(200);
StackPane stackPane = new StackPane();
stackPane.getChildren().add(imageView);
Scene s1 = new Scene(stackPane);
primaryStage.setTitle("Image");
primaryStage.setScene(s1);
primaryStage.show();
}
Thank You
Programming -3
3 Year – first Semester
Lecture 6: JavaFX Layout
Quiz
Q: To create a GUI using JavaFX, which class must be
extended?
A: The Application class, in the package javafx.application
primaryStage.setScene(scene)
;
primaryStage.show();
}
primaryStage.setScene(scene);
primaryStage.show();
}
Layout Panes
• Each pane contains a list for holding nodes in the pane.
This list is an instance of ObservableList, which can be
obtained using pane’s getChildren() method.
• You can use the add(node) method to add an element
to the list, use addAll(node1, node2, ...) to add a
variable number of nodes to the pane.
FlowPane
• It arranges the nodes in the pane horizontally from
left to right or vertically from top to bottom in the
order in which they were added. When one row or
one column is filled, a new row or column is started.
-alignment: ObjectProperty<Pos>
-orientation: ObjectProperty<Orientation>
-hgap: DoubleProperty
-vgap: DoubleProperty
+FlowPane()
+FlowPane(hgap: double, vgap:double)
+FlowPane(orientation:ObjectProperty<Orientation>)
+FlowPane(orientation:ObjectProperty<Orientation>, hgap: double, vgap: double)
FlowPane -- Orientation
Node 5
FlowPane -- Orientation
Node 2
Node 3
Node 4
Node 5
Node 5
flowPaneObject.setAlignment(Pos.TOP_LEFT);
TOP_LEFT, TOP_RIGHT, TOP_CENTER, CENTER_LEFT, CENTER,
CENTER_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT
FlowPane -- Notes
FlowPane -- Padding
Orientation HORIZONTAL
Alignment CENTER_RIGHT
Hgap 20 , Vgap 15
GridPane GridLines
Hgap
Vgap
Node 3 Node 4
gridPaneObject.setHalignment(Node1, HPos.CENTER);
gridPaneObject.setValignment(Node1, VPos.CENTER);
GridPane GridLines
Hgap
Vgap
Node 3 Node 4
Example 2
public void start(Stage primaryStage) {
GridPane pane = new GridPane();
pane.setHgap(10);
pane.setVgap(10);
pane.setPadding(new Insets(20));
Label l1 = new Label("User Name: ");
Label l2 = new Label("Password: ");
TextField tf1 = new TextField();
TextField tf2 = new TextField();
Button b1 = new Button("Login");
pane.add(l1, 0, 0);
pane.add(tf1, 1, 0);
pane.add(l2, 0, 1);
pane.add(tf2, 1, 1);
pane.add(b1, 1, 2);
pane.setHalignment(b1, HPos.CENTER);
Scene s1 = new Scene(pane);
primaryStage.setTitle("GridPane");
primaryStage.setScene(s1);
primaryStage.show();
}
BorderPane
• A BorderPane can place nodes in five regions: top,
bottom, left, right, and center, using the setTop(node),
setBottom(node), setLeft(node), setRight(node), and
setCenter(node) methods.
javafx.scene.layout.BorderPane
-top: ObjectProperty<Node>
-right: ObjectProperty<Node>
-bottom: ObjectProperty<Node>
-left: ObjectProperty<Node>
-center: ObjectProperty<Node>
+BorderPane()
+setAlignment(child: Node, pos:Pos)
TOP
User Name:
LEFT CENTER RIGHT
Password:
BOTTOM
OK
borderPaneObject.setBottom(button1);
borderPaneObject.setAlignment(button1, Pos.CENTER);
borderPaneObject.setRight(circle1);
borderPaneObject.setCenter(anotherPane);
Example 3
public void start(Stage primaryStage) {
BorderPane pane = new BorderPane();
pane.setPadding(new Insets(20));
Button b1 = new Button("Top");
Button b2 = new Button("Bottom");
Button b3 = new Button("Right");
Button b4 = new Button("Left");
Button b5 = new Button("Center");
pane.setTop(b1);
pane.setBottom(b2);
pane.setRight(b3);
pane.setLeft(b4);
pane.setCenter(b5);
pane.setAlignment(b1, Pos.CENTER);
pane.setAlignment(b2, Pos.CENTER);
pane.setAlignment(b3, Pos.CENTER);
pane.setAlignment(b4, Pos.CENTER);
pane.setAlignment(b5, Pos.CENTER);
Scene s1 = new Scene(pane);
primaryStage.setTitle("BorderPane");
primaryStage.setScene(s1);
primaryStage.show();
}
javafx.scene.layout.Vbox
-alignment: ObjectProperty<Pos>
-spacing: DoubleProperty
+VBox()
+VBox(spacing: double)
+setMargin(node: Node, value:Insets): void
Example 4
2
10:35
Shapes
• The Shape class is the abstract base class that defines
the common properties for all shapes. Among them
are the fill, stroke, and strokeWidth properties.
Text
• The Text class defines a node that displays a string at a
starting point (x, y). A Text object is usually placed in a
pane.
javafx.scene.text.Text
-text: StringProperty
-x: DoubleProperty
-y: DoubleProperty
-underline: BooleanProperty
-strikethrough: BooleanProperty
-font: ObjectProperty<Font>
+Text()
+Text(text: String)
+Text(x: double, y: double, text: String)
Example 5
x, y
Text text = new Text(100, 100, “Computer Language”);
text.setUnderline(true);
text.setFill(Color. CADETBLUE);
text.setStroke(Color.BLACK);
text.setStrokeWidth(5);
text.setFont(Font.font("Times New Roman", FontWeight.BOLD,
FontPosture.REGULAR, 80));
text.setRotate(30);
Line
• A line connects two points with four parameters
startX, startY, endX, and endY.
javafx.scene.shape.Line
-startX: DoubleProperty
-startY: DoubleProperty
-endX: DoubleProperty
-endY: DoubleProperty
+Line()
+Line(startX: double, startY:double, endX: double, endY:double)
Example 6
javafx.scene.shape.Rectangle
-x: DoubleProperty
-y:DoubleProperty
-width: DoubleProperty
-height: DoubleProperty
-arcWidth: DoubleProperty
-arcHeight: DoubleProperty
+Rectangle()
+Rectanlge(x: double, y:double, width: double, height: double)
Example 8
public void start(Stage primaryStage) {
Pane pane = new Pane();
for (int i = 0; i < 10; i++) {
Rectangle rectangle = new Rectangle(50 + i*10, 50 + i*10, 160, 100);
rectangle.setFill(Color.color(Math.random(), Math.random(), Math.random()));
rectangle.setArcWidth(15);
rectangle.setArcHeight(15);
pane.getChildren().add(rectangle);
}
Scene s1 = new Scene(pane);
primaryStage.setTitle("Rectangle");
primaryStage.setScene(s1);
primaryStage.show();
}
Task
Circle
• A circle is defined by its parameters centerX, centerY,
and radius.
javafx.scene.shape.Circle
-centerX: DoubleProperty
-centerY: DoubleProperty
-radius: DoubleProperty
+Circle()
+Circle(x: double, y: double)
+Circle(x: double, y: double, radius: double)
Ellipse
Example 10
public void start(Stage primaryStage) {
Pane pane = new Pane();
for (int i = 0; i < 12; i++) {
Arc arc = new Arc(200, 200, 100, 100, i * 30, 30);
arc.setType(ArcType.ROUND);
arc.setFill(Color.color(Math.random(), Math.random(), Math.random()));
pane.getChildren().add(arc);
}
Scene s1 = new Scene(pane);
primaryStage.setTitle("Arc");
primaryStage.setScene(s1);
primaryStage.show();
}
Polygon
• The Polygon class defines a polygon that connects a
sequence of points.
javafx.scene.shape.Polygon
+Polygon()
+Polygon(double... points)
+getPoints():ObservableList<Double>
Polyline
• The Polyline class is similar to the Polygon class except
that the Polyline class is not automatically closed.
javafx.scene.shape.Polyline
+Polyline()
+Polyline(double... points)
+getPoints():ObservableList<Double>
Example 11
public void start(Stage primaryStage) { public void start(Stage primaryStage) {
Pane pane = new Pane(); Pane pane = new Pane();
Polygon polygon = new Polygon(40, 20 , Polyline polyline = new Polyline(40, 20 ,
70 , 40 , 60 , 80 , 45 , 45 , 20 , 60); 70 , 40 , 60 , 80 , 45 , 45 , 20 , 60);
polygon.setStroke(Color.BLACK); polyline.setStroke(Color.BLACK);
polygon.setFill(Color.WHITE); polyline.setFill(Color.WHITE);
pane.getChildren().add(polygon); pane.getChildren().add(polyline);
Scene s1 = new Scene(pane); Scene s1 = new Scene(pane);
primaryStage.setTitle("Polygon"); primaryStage.setTitle("Polyline");
primaryStage.setScene(s1); primaryStage.setScene(s1);
primaryStage.show(); primaryStage.show();
} }
Task
60 140
200
0,0
x
60
100,80
80,120 120,120
5
7
Label class
5
8
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Ellipse;
public class LabelWithGraphic extends Application {
@Override
public void start(Stage primaryStage) {
ImageView us = new ImageView(new Image("us.jpg"));
Label lb1 = new Label("US\n50 States", us);
lb1.setStyle("-fx-border-color: green; -fx-border-width: 2");
lb1.setContentDisplay(ContentDisplay.BOTTOM);
lb1.setTextFill(Color.RED);
Label lb2 = new Label("Circle", new Circle(50, 50, 25));
lb2.setContentDisplay(ContentDisplay.TOP);
lb2.setTextFill(Color.ORANGE);
Label lb3 = new Label("Retangle", new Rectangle(10, 10, 50, 25));
lb3.setContentDisplay(ContentDisplay.RIGHT);
Label lb4 = new Label("Ellipse", new Ellipse(50, 50, 50, 25));
lb4.setContentDisplay(ContentDisplay.LEFT);
5
9
6
0
ButtonBase and Button
A button is a control that triggers an action event when clicked.
JavaFX provides regular buttons, toggle buttons, check box buttons,
and radio buttons.
The common features of these buttons are defined in ButtonBase
and Labeled classes.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
return pane;
}
6
3
CheckBox
A CheckBox is used for the user to make a selection (square box).
CheckBox inherits all the properties from ButtonBase and Labeled:
onAction, text, graphic, alignment, graphicTextGap, textFill,
contentDisplay.
6
(c) Paul Fodor and Pearson Inc.
4
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
text.setFont(fontNormal);
chkBold.setOnAction(handler);
chkItalic.setOnAction(handler);
rbRed.setOnAction(e -> {
if (rbRed.isSelected()) {
text.setFill(Color.RED);
}
13 });
rbGreen.setOnAction(e -> {
if (rbGreen.isSelected()) {
text.setFill(Color.GREEN);
}
});
rbBlue.setOnAction(e -> {
if (rbBlue.isSelected()) {
text.setFill(Color.BLUE);
}
});
return pane;
}
69
TextField
A text field can be used to enter or display a string. TextField isa
subclass ofTextInputControl.
70
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
public class TextFieldDemo extends RadioButtonDemo{
@Override
protected BorderPane getPane() {
BorderPane pane = super.getPane();
return pane;
}
TextArea
A TextArea enables the user to enter multiple lines oftext.
72
ComboBox
A combo box, also known as a choice list or drop-down list,contains
a list of items from which the user can choose.
ListView
A list view is a component that performs basically the same
function as a combo box, but it enables the user to choose a
single value or multiple values.
74
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.SelectionMode;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.collections.FXCollections;
lv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
lv.getSelectionModel().selectedItemProperty().addListener(
ov -> {
imagePane.getChildren().clear();
for (Integer i: lv.getSelectionModel().getSelectedIndices()) {
imagePane.getChildren().add(ImageViews[i]);
}
});
Slider
Slider is similar to ScrollBar, but Slider
has more properties and can appear in
many forms.
Media
The Media class is used to obtain the source of a media type.
The MediaPlayer class is used to play and control the media.
The MediaView class is used to display video.
MediaPlayer
The MediaPlayer class plays and controls media with properties:
autoPlay, currentCount, cycleCount, mute, volume, and
totalDuration.
MediaView
The MediaView class is a subclass of Node that provides a view of the
Media being played by a MediaPlayer.
The MediaView class provides the properties for viewing the media.
JavaFX CSS
JavaFX Cascading Style Sheets (CSS) is based on the W3C CSSand
allows to customize and develop themes for JavaFX controls and
scene graph objects
http://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html
JavaFX uses the prefix "-fx-" to define its vendor CSS properties
(separate from W3CCSS).
A style sheet uses the style class or style id to define styles.
Mutiple style classes can be applied to a single node and a style id to a
unique node.
The syntax .styleclass defines a style class.
The syntax #styleid defines a style id.
Style Class and Style ID
mystyle.css:
.plaincircle {
-fx-fill: white;
-fx-stroke: black;
}
.circleborder {
-fx-stroke-width: 5;
-fx-stroke-dash-array: 12 2 4 2;
}
.border {
-fx-border-color: black;
-fx-border-width: 5;
}
#redcircle {
-fx-fill: red;
-fx-stroke: red;
}
#greencircle {
-fx-fill: green;
-fx-stroke: green;
}
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
public class StyleSheetDemo extends Application {
@Override
public void start(Stage primaryStage) {
HBox hBox = new HBox(5);
Scene scene = new Scene(hBox, 300, 250);
// Load the stylesheet
scene.getStylesheets().add("mystyle.css");
Pane pane1 = new Pane();
Circle circle1 = new Circle(50, 50, 30);
Circle circle2 = new Circle(150, 50, 30);
Circle circle3 = new Circle(100, 100, 30);
pane1.getChildren().addAll(circle1, circle2, circle3);
pane1.getStyleClass().add("border");
circle1.getStyleClass().add("plaincircle"); // Add a style class
circle2.getStyleClass().add("plaincircle"); // Add a style class
circle3.setId("redcircle"); // Add a style id
Pane pane2 = new Pane();
Circle circle4 = new Circle(100, 100, 30);
circle4.getStyleClass().addAll("circleborder", "plainCircle");
circle4.setId("greencircle"); // Add a style class
pane2.getChildren().add(circle4);
pane2.getStyleClass().add("border");
hBox.getChildren().addAll(pane1, pane2);
primaryStage.setTitle("StyleSheetDemo");
primaryStage.setScene(scene);
primaryStage.show();
}
QuadCurve
A quadratic curve is mathematically defined as a quadratic
polynomial.
QuadCurve(double startX, double startY,
double controlX, double controlY, double
endX, double endY)
(controlX, controlY)
(endX, endY)
(startX, startY)
QuadCurve
The getter and setter methods for property values and a getter for property
javafx.scene.shape.QuadCurve itself are provided in the class, but omitted in the UML diagram for brevity.
Menus
Menus make selection easier and are widely used in window
applications.
JavaFX provides five classes that implement menus: MenuBar,
Menu, MenuItem, CheckMenuItem, and
RadioButtonMenuItem.
MenuBar is a top-level menu component used to hold the
menus.
A menu consists of menu items that the user can select (or
toggle on or off).
A menu item can be an instance of MenuItem,
CheckMenuItem, or RadioButtonMenuItem.
Menu items can be associated with nodes and keyboard
37 accelerators.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.geometry.Pos;
@Override
public void start(Stage primaryStage) {
MenuBar menuBar = new MenuBar();
menuItemAdd.setAccelerator(
KeyCombination.keyCombination("Ctrl+A"));
menuItemSubtract.setAccelerator(
KeyCombination.keyCombination("Ctrl+S"));
menuItemMultiply.setAccelerator(
KeyCombination.keyCombination("Ctrl+M"));
menuItemDivide.setAccelerator(
KeyCombination.keyCombination("Ctrl+D"));
HBox hBox1 = new HBox(5);
tfNumber1.setPrefColumnCount(2);
tfNumber2.setPrefColumnCount(2);
39 tfResult.setPrefColumnCount(2);
hBox1.getChildren().addAll(new Label("Number 1:"), tfNumber1,
new Label("Number 2:"), tfNumber2, new Label("Result:"),
tfResult);
hBox1.setAlignment(Pos.CENTER);
double result = 0;
switch (operator) {
case '+': result = number1 + number2; break;
case '-': result = number1 - number2; break;
case '*': result = number1 * number2; break;
case '/': result = number1 / number2; break;
}
tfResult.setText(result + "");
};
96
Context Menu
A context menu (also known as a popup menu) is like a
regular menu, but does not have a menu bar and can float
anywhere on the screen.
Creating a context menu is similar to creating a regular menu.
First, create an instance of ContextMenu, then add MenuItem,
CheckMenuItem, and RadioMenuItem to the context menu.
97
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.image.ImageView;
public class ContextMenuDemo extends Application {
@Override
public void start(Stage primaryStage) {
ContextMenu contextMenu = new ContextMenu();
MenuItem menuItemNew = new MenuItem("New",
new ImageView("image/new.gif"));
MenuItem menuItemOpen = new MenuItem("Open",
new ImageView("image/open.gif"));
MenuItem menuItemPrint = new MenuItem("Print",
new ImageView("image/print.gif"));
MenuItem menuItemExit = new MenuItem("Exit");
contextMenu.getItems().addAll(menuItemNew, menuItemOpen,
menuItemPrint, menuItemExit);
Pane pane = new Pane();
Scene scene = new Scene(pane, 300, 250);
primaryStage.setTitle("ContextMenuDemo");
primaryStage.setScene(scene);
primaryStage.show();
98
pane.setOnMousePressed(
e -> contextMenu.show(pane, e.getScreenX(), e.getScreenY()));
SplitPane
The SplitPane class can be used to display multiple panes and
allow the user to adjust the size of the panes.
TabPane
javafx.scene.control.Control The getter and setter methods for property values and
a getter for property itself are provided in the class, but
omitted in the UML diagram for brevity.
javafx.scene.control.TabPane
-side: ObjectProperty<Side> The position of the tab in the tab pane. Possible values are:
Side.TOP, Side.BOTTOM, Side.LEFT, and Side.RIGHT (default:
Side.TOP).
Creates a default tab pane.
+TabPane()
+getTabs(): ObservableList<Tab> Returns a list of tabs in this tab pane.
java.lang.Object The getter and setter methods for property values and
a getter for property itself are provided in the class, but
omitted in the UML diagram for brevity.
javafx.scene.control.Tab
javafx.scene.control.Control The getter and setter methods for property values and
a getter for property itself are provided in the class, but
omitted in the UML diagram for brevity.
javafx.scene.control.TableView<S>
HTML in JavaFX
HTML intro.: the Internet Web pages format
Example: html_sample_01.html
<!DOCTYPE html>
<html> ← This is the HTML tag. Every HTML page has one
<body>
← This is a paragraph
<p>My first paragraph.</p>
</body>
</html>
HTML
HTML is a language for describing web pages.
HTML stands for Hyper Text Markup Language
HTML is a markup language
A markup language is a set of markup tags
The tags describe document content
HTML documents contain HTML tags and plain text
HTML documents are also called web pages
HTML
HTML markup tags are usually called HTML tags
HTML tags are keywords (tag names) surrounded by angle
brackets like <html>
HTML tags normally come in pairs like <b> and </b>
The first tag in a pair is the start tag, the second tag is
the end tag
The end tag is written like the start tag, with a forward
slash before the tag name
Start and end tags are also called opening tags and closing
tags
<tagname>content</tagname>
<p>This is a paragraph.</p>
HTML by Examples
http://www.w3schools.com/html/html_examples.asp
HTML links:
<a href="http://www.w3schools.com">This is a link</a>
It appears as:This is a link
HTML images:
<img src="w3schools.jpg" width="104" height="142">
It appears as:
Solution: listen to the state of the WebEngine object to know when it is done
loading:
• engine.getLoadWorker().stateProperty().addListener(
• (ObservableValue<? extends State> observable,
• State oldValue, State newValue)
• -> {
• if (newValue == State.SUCCEEDED)
• docManager.setStatsDoc(engine.getDocument()
);
• });
Programming -3
3 Year – first Semester
Lecture 7: Event-Driven Programming
Event-Driven Programming
Say Hello
Event-Driven Programming
• For an object to be handler for an event, two
requirements must be met:
– The object must be an instance of the
EventHandler<T extends Event> interface. You
must overrides the handle(T) method for processing
the action event.
public class mouseHandler implements
EventHandler<MouseEvent> {
@Override
public void handle(MouseEvent event) {
}
}
Event-Driven Programming
– The EventHandler object must be registered with
the event source object using the appropriate
method.
– Ex] for button use
button1.setOnAction(handlerObject);
Example 2
public void start(Stage primaryStage) {
StackPane stackPane = new StackPane();
Circle circle = new Circle(50);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
stackPane.getChildren().add(circle);
HBox hBox = new HBox(10);
hBox.setAlignment(Pos.CENTER);
Button btEnlarge = new Button("Enlarge");
Button btShrink = new Button("Shrink");
hBox.getChildren().add(btEnlarge);
hBox.getChildren().add(btShrink);
BorderPane borderPane = new BorderPane();
borderPane.setCenter(stackPane);
borderPane.setBottom(hBox);
BorderPane.setAlignment(hBox, Pos.CENTER);
Scene scene = new Scene(borderPane, 200, 150);
primaryStage.setTitle("ControlCircle");
primaryStage.setScene(scene);
primaryStage.show();
}
Example 2
• How do you use the buttons to enlarge or shrink the circle?
1. Define a new class named CirclePane for displaying the circle in a
pane. This new class displays a circle and provides the enlarge and
shrink methods for increasing and decreasing the radius of the circle.
2. Create a CirclePane object and declare circlePane as a data field to
reference this object in the ControlCircle class. The methods in the
ControlCircle class can now access the CirclePane object through this
data field.
3. Define a two handlers class named EnlargeHandler and ShrinkHandler
that implement EventHandler<ActionEvent>. To make the reference
variable circlePane accessible from the handle method, define
EnlargeHandler and ShrinkHandler as an inner class of the
ControlCircle class.
4. Register the handlers for the Enlarge and shrink buttona and
implement the handle methods in EnlargeHandler and ShrinkHandler
to invoke circlePane.enlarge() and circlePane.shrink().
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle; 1
public class CirclePane extends StackPane {
import javafx.application.Application;
class EnlargeHandler implements EventHandler<ActionEvent> {
import javafx.event.ActionEvent; @Override
import javafx.event.EventHandler;
import javafx.geometry.Pos; public void handle(ActionEvent event) {
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
circlePane.enLarge(); 3
import javafx.scene.layout.BorderPane; }
import javafx.stage.Stage;
public class ControlCircle extends Application {
}
CirclePane circlePane = new CirclePane();
2 EventHandler<ActionEvent> {
class shrinkHandler implements
public void start(Stage primaryStage) { @Override
HBox hBox = new HBox();
hBox.setSpacing(10);
public void handle(ActionEvent event) {
hBox.setAlignment(Pos.CENTER); circlePane.Shrink();
Button btEnlarge = new Button("Enlarge");
Button btShrink = new Button("Shrink");
}
hBox.setAlignment(Pos.CENTER); }
hBox.getChildren().add(btEnlarge);
hBox.getChildren().add(btShrink);
}
btEnlarge.setOnAction(new EnlargeHandler());
btShrink.setOnAction(new shrinkHandler());
BorderPane borderPane = new BorderPane();
4
borderPane.setCenter(circlePane);
borderPane.setBottom(hBox);
BorderPane.setAlignment(hBox, Pos.CENTER);
Scene scene = new Scene(borderPane, 200, 150);
primaryStage.setTitle("ControlCircle"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
Inner Classes
• Normally, you define a class as an inner class if it is
used only by its outer class. An inner class has the
following features:
– An inner class is compiled into a class named
OuterClassName$InnerClassName.class. For example, the inner class A
in Test is compiled into Test$A.class.
– An inner class can reference the data and the methods defined in the
outer class in which it nests, so you need not pass the reference of an
object of the outer class to the constructor of the inner class. For this
reason, inner classes can make programs simple and concise.
– An inner class can be defined as static. A static inner class can be
accessed using the outer class name. A static inner class cannot access
nonstatic members of the outer class.
Inner Classes
– Objects of an inner class are often created in the outer class. But you
can also create an object of an inner class from another class. If the
inner class is nonstatic, you must first create an instance of the outer
class, then use the following syntax to create an object for the inner
class:
– If the inner class is static, use the following syntax to create an object
for it:
Inner Classes
• A simple use of inner classes is to combine dependent
classes into a primary class. This reduces the number
of source files. It also makes class files easy to
organize since they are all named with the primary
class as the prefix.
• Another practical use of inner classes is to avoid class-
naming conflicts. A handler class is designed
specifically to create a handler object for a GUI
component (e.g., a button). The handler class will not
be shared by other applications and therefore is
appropriate to be defined inside the main class as an
inner class.
Anonymous Inner Classes
• An anonymous inner class is an inner class without a
name. It combines defining an inner class and creating
an instance of the class into one step. Inner-class
handlers can be shortened using anonymous inner
classes.
Example
If you click on first text field print ‘Enter user name here’
If you click on second text field print ‘enter password here’
If you click on Login button print user name and password
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.scene.layout.GridPane;
public class GridPaneTest extends Application {
public void start(Stage primaryStage) {
GridPane pane = new GridPane();
pane.setHgap(10);
pane.setVgap(10);
pane.setPadding(new Insets(20));
Label l1 = new Label("User Name: ");
Label l2 = new Label("Password: ");
TextField tf1 = new TextField();
TextField tf2 = new TextField();
Button b1 = new Button("Login");
pane.add(l1, 0, 0);
pane.add(tf1, 1, 0);
pane.add(l2, 0, 1);
pane.add(tf2, 1, 1);
pane.add(b1, 1, 2);
pane.setHalignment(b1, HPos.CENTER);
tf1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Enter user name here");
}
});
tf2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Enter password here");
}
});
b1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("The User name is " + tf1.getText() + " and password is " +
tf2.getText());
}
});
Example
If you click on first text field print ‘Enter user name here’
If you click on second text field print ‘enter password here’
If you click on Login button print user name and password
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.scene.layout.GridPane;
public class GridPaneTest extends Application {
public void start(Stage primaryStage) {
GridPane pane = new GridPane();
pane.setHgap(10);
pane.setVgap(10);
pane.setPadding(new Insets(20));
Label l1 = new Label("User Name: ");
Label l2 = new Label("Password: ");
TextField tf1 = new TextField();
TextField tf2 = new TextField();
Button b1 = new Button("Login");
pane.add(l1, 0, 0);
pane.add(tf1, 1, 0);
pane.add(l2, 0, 1);
pane.add(tf2, 1, 1);
pane.add(b1, 1, 2);
pane.setHalignment(b1, HPos.CENTER);
tf1.setOnAction(((ActionEvent e) -> {
System.out.println("Enter user name here");
});
tf2.setOnAction((e) -> {
tf2.setOnAction(e -> System.out.println("Enter
System.out.println("Enter password here");password here"));
});
b1.setOnAction(e -> {
System.out.println("The User name is " + tf1.getText() + " and password is " +
tf2.getText());
});
Scene s1 = new Scene(pane);
primaryStage.setTitle("GridPane");
primaryStage.setScene(s1);
primaryStage.show();
Note
• You can handle events by:
– Defining handler classes.
– Inner classes.
– Anonymous inner classes.
– Lambda expressions.
• We recommend that you use lambda expressions
because it produces a shorter, clearer, and cleaner
code.
Mouse Events
• A MouseEvent is fired whenever a mouse button is
pressed, released, clicked, entered, exited, moved, or
dragged on a node or a scene.
javafx.scene.input.MouseEvent
+getButton(): MouseButton
+getClickCount(): int
+getX(): double
+getY(): double
+getSceneX(): double
+getSceneY(): double
+getScreenX(): double
+getScreenY(): double
+isAltDown(): boolean
+isControlDown(): boolean
+isMetaDown(): boolean
+isShiftDown(): boolean
Mouse Events
• The MouseButton defines four constants: PRIMARY,
SECONDARY, MIDDLE, and NONE to indicate the left,
right, middle, and none mouse buttons.
– For example, eventObject.getButton() ==
MouseButton.SECONDARY indicates that the right button
was pressed.
PRIMARY
MIDDLE
SECONDARY
Screen
Mouse Events
Scene
getX()
Node getY()
getSceneX()
Button getSceneY()
getScreenX()
getScreenY()
Screen
Mouse Events
getX()
getY()
Scene getSceneX()
getSceneY()
getScreenX()
Node getScreenY()
Button
Mouse Events
User Action Source Object Event Type Fired Event Registration Method
setOnMousePressed(EventHandler<
Mouse pressed Node, Scene MouseEvent
MouseEvent>)
setOnMouseReleased(EventHandler
Mouse released Node, Scene MouseEvent
<MouseEvent>)
setOnMouseClicked(EventHandler<
Mouse clicked Node, Scene MouseEvent
MouseEvent>)
setOnMouseEntered(EventHandler<
Mouse entered Node, Scene MouseEvent
MouseEvent>)
setOnMouseExited(EventHandler<
Mouse exited Node, Scene MouseEvent
MouseEvent>)
setOnMouseMoved(EventHandler<
Mouse moved Node, Scene MouseEvent
MouseEvent>)
setOnMouseDragged(EventHandler
Mouse dragged Node, Scene MouseEvent
<MouseEvent>)
Mouse Events
• Three ways to handle mouse events:
– Inner Class.
• Class must implement EventHandler<EventType event> and
overrides handle method.
– Anonymous Inner Class.
• Like Inner class, but we write implementation of inner class as a
parameter when registering handler. We remove “class className
implements” to be anonymous.
– Lambda Expressions
• Like the concept of anonymous inner class. It removes class
declaration, method header, and retains only eventObject. After event
Object, it writes symbol -> and then expressions and statements to be
executed.
Example 1
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
}
Inner Class
circle.setFill(Color.BLACK);
}
class MouseReleasedHandler implements EventHandler<MouseEvent> {
@Override
public void handle(MouseEvent event) {
circle.setFill(Color.WHITE);
}
}
}
Mouse Events
circle.setOnMousePressed(new MousePressedHandler());
circle.setOnMousePressed(new EventHandler<MouseEvent> () {
@Override
public void handle(MouseEvent event) {
circle.setFill(Color.BLACK);
}
});
Mouse Events
circle.setOnMouseReleased(new MouseReleasedHandler());
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
Mouse Events
circle.setOnMousePressed(new EventHandler<MouseEvent> () {
@Override
public void handle ( MouseEvent event) {
circle.setFill(Color.BLACK);
}
});
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
Example 2
circle.setOnMouseClicked(event -> {
if (event.getButton() == MouseButton.PRIMARY) {
circle.setFill(Color.color(Math.random(), Math.random(), Math.random()));
} else if (event.getButton() == MouseButton.SECONDARY) {
circle.setStroke(Color.color(Math.random(), Math.random(), Math.random()));
}
});
Scene scene = new Scene(stackPane, 200, 200);
primaryStage.setScene(scene);
primaryStage.setTitle("Mouse Event Handler");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Key Events
• A KeyEvent is fired whenever a key is pressed,
released, or typed on a node or a scene.
javafx.scene.input.KeyEvent
+getCharacter(): String
+getCode(): KeyCode
+getText(): String
+isAltDown(): boolean
+isControlDown(): boolean
+isMetaDown(): boolean
+isShiftDown(): boolean
Key Events
• The key codes are constants defined in KeyCode class.
• For the key-pressed and key-released events:
– getCode() returns the value associated with key (ex,
KeyCode.A)
– getText() returns a string that describes the key code
– getCharacter() returns an empty string.
• For the key-typed event:
– getCode() returns UNDEFINED
– getText() returns an empty string.
– getCharacter() returns the character or a sequence of
characters associated with the key-typed event.
Key Events
KeyCode Constants
Key Events
User Action Source Object Event Type Fired Event Registration Method
setOnKeyPressed(EventHandler<KeyE
Key pressed Node, Scene MouseEvent
vent>)
setOnKeyReleased(EventHandler<Key
Key released Node, Scene MouseEvent
Event>)
setOnKeyTyped(EventHandler<KeyEve
Key Typed Node, Scene MouseEvent
nt>)
Example 2
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class KeyEvent extends Application {
Circle circle = new Circle(150);
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
circle.setStrokeWidth(4);
circle.setCenterX(300);
circle.setCenterY(300);
pane.getChildren().add(circle);
Scene scene = new Scene(pane, 600, 600);
circle.requestFocus();
circle.setOnKeyPressed(event -> {
if (event.getText().equals("h")) {
circle.setRadius(circle.getRadius() + 5);
} else if (event.getText().equals("l")) {
circle.setRadius(circle.getRadius() - 5);
} else if (event.getCode() == KeyCode.UP) {
circle.setCenterY(circle.getCenterY() - 10);
} else if (event.getCode() == KeyCode.DOWN) {
circle.setCenterY(circle.getCenterY() + 10);
} else if (event.getCode() == KeyCode.LEFT) {
circle.setCenterX(circle.getCenterX() - 10);
} else if (event.getCode() == KeyCode.RIGHT) {
circle.setCenterX(circle.getCenterX() + 10);
}
});
circle.setOnMouseClicked(event -> {
if (event.getButton() == MouseButton.PRIMARY) {
circle.setFill(Color.color(Math.random(), Math.random(), Math.random()));
} else if (event.getButton() == MouseButton.SECONDARY) {
circle.setStroke(Color.color(Math.random(), Math.random(), Math.random()));
}
});
primaryStage.setScene(scene);
primaryStage.setTitle("Key Event");
є
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
CSS IN JAVAFX
What is CSS?
• CSS (Cascading Style Sheets) is a design
language which is used to enhance the
appearance of the web pages without changing its
functionality. It only deals with the way, a web
page is presented on the web browser.
• Using CSS, we can define the color, size, font
styles, spacing between the paragraph, alignment
and many more thing for a web page so that it can
look more precise and better. We can also
configure the background of the application,
layout, design and variety of display for the
different size devises.
CSS in JavaFX
• JavaFX, being the new generation UI library, provides
the facility to configure the theme of the application.
JavaFX provides the package javafx.css which
contains all the classes to apply the CSS to the
JavaFX application.
• Applying CSS to the JavaFX application is similar to
applying CSS to the HTML page.
• JavaFX uses caspian.css as the default CSS file. It is
found in JavaFX Run time JAR file, jfxrt.jar. This style
sheet defines the default style rules for the root node
and UI controls. This file is located at the
path /jre/lib under the JDK installation directory.
Programming -3
3 Year – first Semester
Lecture 7: JavaFX UI Controls and Multimedia
Agenda
• JavaFX UI Controls and Multimedia
– Labeled and Label
– Button
– CheckBox
– RadioButton
– TextField
– TextArea
– ComboBox
– ListView
– ScrollBar
– Slider
– Video and Audio
Introduction
ToggleButton RadioButton
Slider
TextArea
TextInputControl
TextField PasswordField
ListView
ComboBoxBase ComboBox
Labeled Class
javafx.scene.control.Labeled
Specifies the alignment of the text and
-alignment: ObjectProperty<Pos>
node in the labeled.
Specifies the position of the node relative
-contentDisplay: to the text using the constants TOP,
ObjectProperty<ContentDisplay> BOTTOM, LEFT, and RIGHT defined in
ContentDisplay.
-graphic: ObjectProperty<Node> A graphic for the labeled.
-graphicTextGap: DoubleProperty The gap between the graphic and the text.
-textFill: ObjectProperty<Paint> The paint used to fill the text.
-text: StringProperty A text for the labeled.
-underline: BooleanProperty Whether text should be underlined.
Whether text should be wrapped if the text
-wrapText: BooleanProperty
exceeds the width.
javafx.scene.control.Label
+Label() Creates an empty label.
+Label(text: String) Creates a label with the specified text.
Creates a label with the specified text and
+Label(text: String, graphic: Node)
graphic.
Labeled and Label
Label label = new Label();
label.setText("Computer Language");
label.setAlignment(Pos.TOP_RIGHT);
label.setContentDisplay(ContentDisplay.RIGHT);
label.setGraphic(new Circle(20));
label.setGraphicTextGap(10);
label.setTextFill(Color.BLUE);
label.setUnderline(true);
label.setWrapText(true);
Button
• A button is a control that triggers an action event
when clicked.
• JavaFX provides regular buttons, toggle buttons, check
box buttons, and radio buttons.
• The common features of these buttons are defined in
ButtonBase and Labeled classes.
javafx.scene.control.ButtonBase
-onAction: ObjectProperty<EventHandler Defines a handler for handling a
<ActionEvent>> button’s action.
Button
• A Button can be constructed using one of the three
constructors.
javafx.scene.control.Button
+Button() Creates an empty button.
+Button(text: String) Creates a button with the specified text.
+Button(text: String, graphic: Creates a button with the specified text
Node) and graphic.
Button
CheckBox
RadioButton
• A Radio Button can be constructed using one of the
two constructors.
javafx.scene.control.RadioButton
+RadioButton() Creates an empty radio button.
+RadioButton(text: String) Creates a radio button with the
specified text.
TextField
• A text field can be used to enter or display a string.
• TextField is a subclass of TextInputControl.
javafx.scene.control.TextInputControl
-text: StringProperty The text content of this control.
Indicates whether the text can be edited by
-editable: BooleanProperty
the user.
TextField
TextArea
Label label1 = new Label("User name:");
Label label2 = new Label("Password:");
Label label3 = new Label("Message:");
TextField textField = new TextField();
PasswordField passwordField = new PasswordField();
TextArea textArea = new TextArea();
textArea.setPrefRowCount(5);
textArea.setWrapText(true);
GridPane pane = new GridPane();
pane.setPadding(new Insets(15));
pane.setHgap(10);
pane.setVgap(10);
pane.addRow(0, label1,textField);
pane.addRow(1, label2,passwordField);
pane.addRow(2, label3,textArea);
TextArea
Label label1 = new Label("User name:");
Label label2 = new Label("Password:");
Label label3 = new Label("Message:");
TextField textField = new TextField();
PasswordField passwordField = new PasswordField();
TextArea textArea = new TextArea();
textArea.setPrefRowCount(20);
textArea.setPrefColumnCount(15);
textArea.setWrapText(true);
ScrollPane scrollPane = new ScrollPane(textArea);
GridPane pane = new GridPane();
pane.setPadding(new Insets(15));
pane.setHgap(10);
pane.setVgap(10);
pane.addRow(0, label1,textField);
pane.addRow(1, label2,passwordField);
pane.addRow(2, label3, scrollPane);
ComboBox
• A combo box (i.e., choice list or drop-down list)
contains a list of items from which the user can
choose.
• A combo box is useful for limiting a user’s range of
choices.
• ComboBox is a subclass of ComboBoxBase class.
javafx.scene.control.ComboBoxBase<T>
-value: ObjectProperty<T> The value selected in the combo box.
Specifies whether the combo box allows
-editable: BooleanProperty
user input.
-onAction:
Specifies the handler for processing the
ObjectProperty<EventHandler
action event.
<ActionEvent>>
ComboBox
• A ComboBox can be constructed using one of the two
constructors.
javafx.scene.control.ComboBox<T>
-items:
The items in the combo box popup.
ObjectProperty<ObservableList<T>>
The maximum number of visible rows
-visibleRowCount: IntegerProperty
of the items in the combo box popup.
+ComboBox() Creates an empty combo box.
Creates a combo box with the specified
+ComboBox(items: ObservableList<T>)
items.
ComboBox
Example 1
HBOX
VBOX
GridPane Pane
HBox
BorderPane
public void start(Stage primaryStage) {
textField.setOnAction(e -> {
text.setText(textField.getText());
});
radioButton1.setOnAction(e -> {
text.setFill(Color.RED);
});
radioButton2.setOnAction(e -> {
text.setFill(Color.GREEN);
});
radioButton3.setOnAction(e -> {
text.setFill(Color.BLUE);
});
checkBox1.setOnAction(e -> {
if(checkBox1.isSelected() && checkBox2.isSelected()){
text.setFont(Font.font("Times New Roman", FontWeight.BOLD,
FontPosture.ITALIC, comboBox.getValue()));
}
else if (checkBox1.isSelected() && !checkBox2.isSelected() ){
text.setFont(Font.font("Times New Roman", FontWeight.BOLD,
FontPosture.REGULAR, comboBox.getValue()));
}
else if (!checkBox1.isSelected() && checkBox2.isSelected()){
text.setFont(Font.font("Times New Roman",FontWeight.NORMAL,
FontPosture.ITALIC, comboBox.getValue()));
}
else if( !checkBox1.isSelected() && !checkBox2.isSelected()){
text.setFont(Font.font("Times New Roman", FontWeight.NORMAL,
FontPosture.REGULAR, comboBox.getValue()));
}
});
checkBox2.setOnAction(e -> {
if(checkBox1.isSelected() && checkBox2.isSelected()){
text.setFont(Font.font("Times New Roman", FontWeight.BOLD,
FontPosture.ITALIC, comboBox.getValue()));
}
else if (checkBox1.isSelected() && !checkBox2.isSelected() ){
text.setFont(Font.font("Times New Roman", FontWeight.BOLD,
FontPosture.REGULAR, comboBox.getValue()));
}
else if (!checkBox1.isSelected() && checkBox2.isSelected()){
text.setFont(Font.font("Times New Roman",FontWeight.NORMAL,
FontPosture.ITALIC, comboBox.getValue()));
}
else if( !checkBox1.isSelected() && !checkBox2.isSelected()){
text.setFont(Font.font("Times New Roman", FontWeight.NORMAL,
FontPosture.REGULAR, comboBox.getValue()));
}
});
ListView
• The getSelectionModel() method returns an instance
of SelectionModel, which contains the methods for
setting a selection mode and obtaining selected
indices and items.
• The selection mode is defined in one of the two
constants: SelectionMode.MULTIPLE and
SelectionMode.SINGLE, which indicates whether a
single item or multiple items can be selected. The
default value is SelectionMode.SINGLE.
ListView
• To return selected indices:
obj.getSelectionModel().getSelectedIndices();
• To return selected items:
obj.getSelectionModel().getSelectedItems());
• To handle event:
obj.getSelectionModel().selectedItemProperty().addListener(ov ->
{
Statements;
});
ListView
ListView
String[] cities = {"Cairo", "Alex", "Aswan", "Sharm"};
ImageView imageView1 = new ImageView("image/cairo.jpg");
ImageView imageView2 = new ImageView("image/alex.jpg");
ImageView imageView3 = new ImageView("image/aswan.jpg");
ImageView imageView4 = new ImageView("image/sharm.jpg");
imageView1.setFitWidth(200);
imageView1.setFitHeight(200);
imageView2.setFitWidth(200);
imageView2.setFitHeight(200);
imageView3.setFitWidth(200);
imageView3.setFitHeight(200);
imageView4.setFitWidth(200);
imageView4.setFitHeight(200);
ListView
// Create a pane to hold image views
FlowPane imagePane = new FlowPane(10, 10);
BorderPane pane = new BorderPane();
pane.setLeft(new ScrollPane(listView));
pane.setCenter(imagePane);
listView.getSelectionModel().selectedItemProperty().addListener(
ov -> {
imagePane.getChildren().clear();
for (Integer i : listView.getSelectionModel().getSelectedIndices()) {
imagePane.getChildren().add(citiesPhoto[i]);
}
}
);
MEDIA
javafx.scene.media.MediaPlayer
Specifies whether the playing should start
-autoPlay: BooleanProperty
automatically.
-currentCount: ReadOnlyIntegerProperty The number of completed playback cycles.
Specifies the number of time the media
-cycleCount: IntegerProperty
will be played.
-mute: BooleanProperty Specifies whether the audio is muted.
-volume: DoubleProperty The volume for the audio.
The amount of time to play the media
-totalDuration: ReadOnlyObjectProperty<Duration>
from start to finish.
+MediaPlayer(media: Media) Creates a player for a specified media.
+play(): void Plays the media.
+pause(): void Pauses the media.
+seek(): void Seeks the player to a new playback time.
Video and Audio
• The MediaView class is a subclass of Node that
provides a view of the Media being played by a
MediaPlayer.
javafx.scene.media.MediaView
-mediaPlayer:
Specifies a media player for the media view.
ObjectProperty<MediaPlayer>
Specifies the width of the view for the media
-fitWidth: DoubleProperty
to fit.
Specifies the height of the view for the
-fitHeight: DoubleProperty
media to fit.
+MediaView() Creates an empty media view.
+MediaView(mediaPlayer: Creates a media view with the specified
MediaPlayer) media player
Audio Steps
• Instantiate the javafx.scene.media.Media class by
passing the location of the audio file in its constructor.
Use the following line of code for this purpose.
Media media = new Media("http://path/file_name.mp3");
• Pass the Media class object to the new instance
of javafx.scene.media.MediaPlayer object.
Mediaplayer mediaPlayer = new MediaPlayer(media);
• Invoke the MediaPlayer object's play() method when
onReady event is triggered.
MediaPlayer.setAutoPlay(true);
Playing Audio
1. public void start (Stage primaryStage) throws Exception {
2. // TODO Auto-generated method stub
3. //Initialising path of the media file, replace this with your file path
4. String path = "/home/javatpoint/Downloads/test.mp3";
5.
6. //Instantiating Media class
7. Media media = new Media(new File(path).toURI().toString());
8.
9. //Instantiating MediaPlayer class
10. MediaPlayer mediaPlayer = new MediaPlayer(media);
11.
12. //by setting this property to true, the audio will be played
13. mediaPlayer.setAutoPlay(true);
14. primaryStage.setTitle("Playing Audio");
15. primaryStage.show();
16. }
Video steps
• Instantiate the javafx.scene.media.Media class by passing
the location of the audio file in its constructor. Use the
following line of code for this purpose.
Media media = new Media("http://path/file_name.mp3");
• Pass the Media class object to the new instance
of javafx.scene.media.MediaPlayer object.
Mediaplayer mediaPlayer = new MediaPlayer(media);
• Invoke the MediaPlayer object's play() method when onReady
event is triggered.
mediaPlayer.setAutoPlay(true);
• Instantiate MediaView class and pass Mediaplayer object into
its constructor.
MediaView mediaView = new MediaView (mediaPlayer)
Video steps
• Add the MediaView Node to the Group
and configure Scene.
Group root = new Group();
root.getChildren().add(mediaView)
Scene scene = new Scene(root,600,400);
primaryStage.setTitle("Playing Video");
primaryStage.show();
Playing video
Public
void start(Stage primaryStage) throws Exce
ption { mediaPlayer.setAutoPlay(
true);
// TODO Auto-generated method stub
//Initialising path of the media file, replac //setting group and scene
e this with your file path
String path = "/home/javatpoint/Downlo Group root = new Group()
ads/test.mp4"; ;
//Instantiating Media class root.getChildren().add(me
Media media = new Media(new File(pat diaView);
h).toURI().toString()); Scene scene = new Scen
e(root,500,400);
//Instantiating MediaPlayer class
primaryStage.setScene(sc
ene);
MediaPlayer mediaPlayer = new Media primaryStage.setTitle("Pla
Player(media); ying video");
//Instantiating MediaView class primaryStage.show();
MediaView mediaView = new MediaVie }
w(mediaPlayer);
Video and Audio
URL mediaUrl = getClass().getResource("Test.mp4");
String mediaStringUrl = mediaUrl.toExternalForm();
Media media = new Media(mediaStringUrl);
MediaPlayer mediaPlayer = new MediaPlayer(media);
MediaView mediaView = new
MediaView(mediaPlayer);
Button playButton = new Button(">");
playButton.setOnAction(e -> {
if (playButton.getText().equals(">")) {
mediaPlayer.play();
playButton.setText("||");
} else {
mediaPlayer.pause();
playButton.setText(">");
}
});
Button rewindButton = new Button("<<");
rewindButton.setOnAction(e ->
mediaPlayer.seek(Duration.ZERO));
Agenda
• Threading and Parallel Programming
– Introduction – Cooperation among Threads
Quiz
• How can multiple threads run simultaneously in a
single-processor system?
The multiple threads share the CPU time in a single-
processor system.
• What is a thread?
A thread is an object that facilitates the execution of a
task.
Creating Tasks and Threads
• To create tasks:
1. You have to first define a class for each task.
2. The class must implement the Runnable interface.
3. The Runnable interface contains only the run() method.
4. You need to implement this method to tell the system how
your thread is going to run.
public class Task implements Runnable {
}
}
}
}
This program will print Ali 5 times then print Aya 5 times
Quiz
public class Task implements Runnable { public class Test {
String message; public static void main(String[] args) {
public Task (String msg) { // create two instances of Task
message = msg; Task t1 = new Task(“Ali”);
} Task t2 = new Task(“Aya”);
• aaabbbb123aaaaabbbb786abb91045a
Example
class PrintChar implements Runnable {
private char ch;
private int times;
public PrintNum(int n) {
lastNum = n;
}
Example
public class Example {
public static void main(String[] args) {
Runnable printA = new PrintChar('a', 10); Output:
Runnable printB = new PrintChar('b', 10); aa 1 2bb 3a 4bbbbbbb 5 6 7 8
Runnable print10 = new PrintNum(10); 9a 10baaaaaa
If you thread1.start();
replace the start() method by the run() method, the
thread1.run();
run() method are executed in sequence.
thread2.start(); The threads are
thread2.run();
not executed concurrently.
thread3.start(); thread3.run();
• What is wrong in the following two programs?
Thread Class
• The Thread class contains the constructors for creating
threads for tasks and the methods for controlling threads.
java.lang.Thread
+Thread(task: Runnable) Creates a thread for a specified task.
+Thread() Creates an empty thread.
Starts the thread that causes the run() method to be
+start(): void
invoked by the JVM.
+isAlive(): boolean Tests whether the thread is currently running.
+setPriority(p: int): void Sets priority p (ranging from 1 to 10) for this thread.
+join(): void Waits for this thread to finish. (blocked state)
Puts a thread to sleep for a specified time in
+sleep(millis: long): void
milliseconds. (blocked state)
Causes a thread to pause temporarily and allow other
+yield(): void
threads to execute. (ready state)
+interrupt(): void Interrupts this thread. (blocked state)
Thread Class
• The Thread class implements Runnable.
But is not recommended because it mixes the task and the mechanism of running
the task.
Thread Class
• Thread class also contains the stop(), suspend(), and
resume() methods.
• As of Java 2, these methods were deprecated (or
outdated) because they are known to be inherently
unsafe.
• Instead of using the stop() method, you should assign
null to a Thread variable to indicate that has stopped.
thread1 = null;
Thread Class
• You can use the yield() method to temporarily release
time for other threads. Ex] suppose you modify the
code in the run() method for PrintNum as follows:
public void run() {
for(int i = 1; i <= lastNum; i++) {
System.out.print(" "+ i);
Thread.yield();
}
}
• Every time a number is printed, the thread of the
print10 task is yielded to other threads.
Thread Class
• The sleep(long millis) method puts the thread to
sleep for a specified time in milliseconds to allow
other threads to execute. Every time a number
public void run() { (>= 5) is printed, the
try{
thread of the print10
for(inti =1; i <= lastNum; i++) {
System.out.print(" "+ i); task is put to sleep for
if(i >= 5) { 100 millisecond. The
Thread.sleep(100); sleep method may
} throw an
} InterruptedException,
} which is a checked
catch(InterruptedException ex) { exception.
}
}
Thread Class
• If a sleep method is invoked in a loop, you should
wrap the loop in a try-catch block.
Thread Class
• You can use the join() method to force one thread to
wait for another thread to finish.
A new thread4 is created and it prints character c 40 times. The numbers from 50
to 100 are printed after thread thread4 is finished.
Thread Class
• Java assigns every thread a priority.
– By default, a thread inherits the priority of the thread that
spawned it.
• You can increase or decrease the priority of any
thread by using the setPriority method, and you can
get the thread’s priority by using the getPriority
method.
– Priorities are numbers ranging from 1 to 10. The Thread
class has the int constants MIN_PRIORITY, NORM_PRIORITY,
and MAX_PRIORITY, representing 1, 5, and 10, respectively.
• The priority of the main thread is
Thread.NORM_PRIORITY.
Thread Class
• The JVM always picks the currently runnable thread
with the highest priority.
• A lower priority thread can run only when no higher-
priority threads are running.
• If all runnable threads have equal priorities, each is
assigned an equal portion of the CPU time in a circular
queue. This is called round-robin scheduling.
• For example, suppose you insert the following code:
thread3.setPriority(Thread.MAX_PRIORITY);
Quiz
• How do you set a priority for a thread? What is the
default priority?
You use the setPriority() method to set the priority for a
thread. The default priority of the thread is
Thread.NORM_PRIORITY.
Thread Pool
• The previous approach is convenient for a single task
execution, but it is not efficient for a large number of
tasks because you have to create a thread for each
task.
• Starting a new thread for each task could limit
throughput and cause poor performance.
• Using a thread pool is an ideal way to manage the
number of tasks executing concurrently.
• Java provides the Executor interface for executing
tasks in a thread pool and the ExecutorService
interface for managing and controlling tasks.
Thread Pool
«interface» java.util.concurrent.Executor
+execute(Runnable object): void Executes the runnable task.
«interface» java.util.concurrent.ExecutorService
Shuts down the executor, but allows the tasks
+shutdown(): void in the executor to complete. Once shut down, it
cannot accept new tasks.
Shuts down the executor immediately even
+shutdownNow():
though there are unfinished threads in the pool.
List<Runnable>
Returns a list of unfinished tasks.
Returns true if the executor has been shut
+isShutdown(): boolean
down.
Returns true if all tasks in the pool are
+isTerminated(): boolean
terminated.
ExecutorService is a subinterface of Executor.
Thread Pool
• To create an Executor object, use the static methods
in the Executors class.
java.util.concurrent.Executors
Creates a thread pool with a fixed number of
+newFixedThreadPool(numberO threads executing concurrently. A thread may
fThreads: int): ExecutorService be reused to execute another task after its
current task is finished.
Creates a thread pool that creates new threads
+newCachedThreadPool():
as needed, but will reuse previously
ExecutorService
constructed threads when they are available.
Thread Pool
• The newFixedThreadPool(int) method creates a fixed
number of threads in a pool. If a thread completes
executing a task, it can be reused to execute another
task. If a thread terminates due to a failure prior to
shutdown, a new thread will be created to replace it.
Thread Pool
import java.util.concurrent.*;
Quiz
• How do you create a thread pool with three fixed
threads?
ExecutorService executor =
Executors.newFixedThreadPool(3);
37
Thread States
• A thread state indicates the status of thread. Tasks are
executed in threads. Threads can be in one of five states
New, Ready, Running, Blocked, or Finished.
• Notes:
– When a thread is newly created, it enters the New state.
– After a thread is started by calling its start() method, it enters
the Ready state.
– A ready thread is runnable but may not be running yet.
– The operating system has to allocate CPU time to it.
– When a ready thread begins executing, it enters the Running
state.
– A running thread can enter the Ready state if its given CPU
time expires or its yield() method is called.
Thread States
Thread States
• A thread can enter the Blocked state (i.e., become inactive)
for several reasons. It may have invoked the join(), sleep(), or
wait() method.
• It may be waiting for an I/O operation to finish.
• For example, if a thread has been put to sleep and the sleep
time has expired, the thread is reactivated and enters the Ready
state.
• Finally, a thread is Finished if it completes the execution of its
run() method.
Thread States
• Notes:
– The isAlive() method is used to find out the state of a
thread. It returns true if a thread is in the Ready,
Blocked, or Running state; it returns false if a thread is
new and has not started or if it is finished.
– The interrupt() method interrupts a thread in the
following way: If a thread is currently in the Ready or
Running state, its interrupted flag is set; if a thread is
currently blocked, it is awakened and enters the
Ready state, and a java.lang.InterruptedException is
thrown.
– Example:
– public synchronized void updateRecord() {
– //**** critical code goes here …
– }
• Only one thread may be inside the body of this function. A second call
will be blocked until the first call returns or wait() is called inside the
synchronized method.
44
Synchronization of Java Threads
If you don’t need to protect an entire method, you can
synchronize on an object:
public void foo() {
synchronized (this) {
//critical code goes here …
}
…
}
45
Synchronization of Java Threads
• here are two ways by which we can achieve or implement
synchronization in Java. That is, we can synchronize the
object. They are:
• Synchronized Method
• Synchronized Block
• Any synchronized instance method can be converted into a
synchronized statement. For example, the following
synchronized instance method in (a) is equivalent to (b):
(a) (b)
Realtime Example of
Synchronization in Java
• Suppose a thread in a program is reading a
record from a file while another thread is still
writing the same file. In this situation, the
program may produce undesirable output.
• Let’s take a scenario of railway reservation
system where two passengers are trying to
book seats from Dhanbad to Delhi in
Rajdhani Express. Both passengers are
trying to book tickets from different locations.
Thread Synchronization
• Thread synchronization is to coordinate the execution of
the dependent threads.
– A shared resource may become corrupted if it is accessed
simultaneously by multiple threads.
• Example:
– Suppose you create and launch 100 threads, each of which
adds a penny ( )مبلغ من المالto an account. Define a class named
Account to model the account, a class named AddAPennyTask
to add a penny to the account, and a main class that creates
and launches threads.
Example 2
import java.util.concurrent.*;
Example
Thread Synchronization
Task 1 does nothing because in Step 4 Task 2 overrides Task 1’s result
Thread Synchronization
• The problem is that Task 1 and Task 2 are accessing a
common resource in a way that causes a conflict.
• This is a common problem, known as a race condition, in
multithreaded programs.
• A class is said to be thread-safe if an object of the class
does not cause a race condition in the presence of
multiple threads.
• As demonstrated in the preceding example, the Account
class is not thread-safe.
Thread Synchronization
• To avoid race conditions, it is necessary to prevent more
than one thread from simultaneously entering a certain
part of the program, known as the critical region.
– The critical region in previous Example is the entire deposit
method.
• You can use the keyword synchronized to synchronize
the method so that only one thread can access the
method at a time.
public synchronized void deposit(int amount)
• A synchronized method acquires a lock before it
executes.
Thread Synchronization
• A lock is a mechanism for exclusive use of a resource.
– In the case of an instance method, the lock is on the object for
which the method was invoked.
– In the case of a static method, the lock is on the class.
• If one thread invokes a synchronized instance method
(respectively, static method) on an object, the lock of
that object (respectively, class) is acquired first, then the
method is executed, and finally the lock is released.
Another thread invoking the same method of that object
(respectively, class) is blocked until the lock is released.
Thread Synchronization
• With the deposit method synchronized, the preceding
scenario cannot happen. If Task 1 enters the method,
Task 2 is blocked until Task 1 finishes the method.
PARALLEL PROGRAMMING
Parallel Programming
• The widespread use of multicore systems has created a revolution in
software. In order to benefit from multiple processors, software needs
to run in parallel.
• JDK 7 introduces the new Fork/Join Framework for parallel
programming, which utilizes the multicore processors.
• A problem is divided into nonoverlapping subproblems, which can
be solved independently in parallel. The solutions to all subproblems
are then joined to obtain the overall solution for the problem.
• This is the parallel implementation of the divide-and-conquer
approach
• Fork/Join Framework, a fork can be viewed as an
independent task that runs on a thread.
Fork/Join Framework
Fork/Join Framework
• The framework defines a task using the ForkJoinTask
class, and executes a task in an instance of
ForkJoinPool.
• The tasks are primarily coordinated using fork() and
join().
• Invoking fork() on a task arranges asynchronous
execution, and invoking join() waits until the task is
completed.
• The invoke() and invokeAll(tasks) methods implicitly
invoke fork() to execute the task and join() to wait for
the tasks to complete, and return the result, if any.
Merge Sort Example
• We now use a merge sort to demonstrate how to
develop parallel programs using the Fork/Join
Framework.
• The merge sort algorithm divides the array into two
halves and applies a merge sort on each half
recursively.
• After the two halves are sorted, the algorithm merges
them. Next Program gives a parallel implementation
of the merge sort algorithm and compares its
execution time with a sequential sort.
• import java.util.concurrent.RecursiveAction;
• import java.util.concurrent.ForkJoinPool;
• public class ParallelMergeSort {
• public static void main(String[] args) {
• final int SIZE = 7000000;
• int[] list1 = new int[SIZE];
• int[] list2 = new int[SIZE];
•
• for (int i = 0; i < list1.length; i++)
• list1[i] = list2[i] = (int)(Math.random() *
10000000);
•
• long startTime = System.currentTimeMillis();
• parallelMergeSort(list1); // Invoke parallel
merge sort
• long endTime = System.currentTimeMillis();
• System.out.println("\nParallel time with "
• + Runtime.getRuntime().availableProcessors()
+
• " processors is " + (endTime - startTime) +
" milliseconds");
• startTime =
System.currentTimeMillis();
• MergeSort.mergeSort(list2);
• endTime =
System.currentTimeMillis();
•
System.out.println("\nSequential
time is " +
• (endTime - startTime) + "
milliseconds");
• }
Parallel Programming
• In general, a problem can be solved in parallel using the
following pattern:
•if (the program is small)
• solve it sequentially;
•else {
• divide the problem into nonoverlapping subproblems;
• solve the subproblems concurrently;
• combine the results from subproblems to solve the
whole problem;
• }
Quiz
1. How do you define a ForkJoinTask? What
are the differences between RecursiveAction and
RecursiveTask?
Thank You
Programming -3
3 Year – first Semester
Lecture 10: Networking in java
Agenda
• Networking Programming
– Introduction – What is networking?
– Protocols – Protocols
– Java.net Package
Introduction
• Networking: is the concept of connecting a group of 2
or more machines.
• Java Networking is a concept of connecting two or
more computing devices together so that we can
share resources.
• Java socket programming provides facility to share
data between different computing devices.
•
Protocols
• Protocols help in passing information from
one computer to another.
• Internet protocol (IP): is the
network protocol used to
send information from one
computer to another over
the internet.
• Transmission control
protocols (TCP) or user
datagram protocols (UDP):
are a higher level protocols.
Java Networking Terminology
• The widely used Java networking
terminologies are given below:
– IP Address
– Protocol
– Port Number
– MAC Address
– Connection-oriented and connection-less protocol
– Socket
• IP Address
• IP address is a unique number assigned to a
node of a network e.g. 192.168.0.1 . It is
composed of octets that range from 0 to 255.
• It is a logical address that can be changed.
• 2) Protocol
• A protocol is a set of rules basically that is
followed for communication. For example:
• TCP, FTP, Telnet, SMTP, POP etc
• Port Number
• The port number is used to uniquely identify different
applications. It acts as a communication endpoint
between applications.
• The port number is associated with the IP address for
communication between two applications.
• 4) MAC Address
• MAC (Media Access Control) address is a unique
identifier of NIC (Network Interface Controller).
• A network node can have multiple NIC but each with
unique MAC address.
• For example, an ethernet card may have
a MAC address of 00:0d:83::b1:c0:8e.
Client/Server Architecture
• The client makes the
request to the server
and the server
responds by providing
the required service to
the client.
• Clients communicate
through client sockets
and servers
communicate through
server socket.
Commonly used protocols
• The communication of computers is possible
using ports.
• UDP
• UDP
• TCP
• TCP
InetAddress class
• Java InetAddress class represents an IP
address.
• The java.net.InetAddress class provides
methods to get the IP of any host name for
example www.javatpoint.com,
www.google.com, www.facebook.com, etc.
• Java InetAddress class is used to
encapsulate both numerical ip address
and the domain name for that address.
Java URL
• import java.net.*;
• class URLDemo{
• public static void main(String[] args){
• try{
• URL url=new
URL("http://www.google.com:80/index.htm");
• System.out.println("Protocol: "+url.getProtocol());
• System.out.println("Host Name: "+url.getHost());
• System.out.println("Port Number: "+url.getPort());
• System.out.println("File Name: "+url.getFile()); }
• catch(Exception e){
• System.out.println(e);
• } } }
Reading data
• After a URL object is created, you can use the openStream()
method defined in the URL class to open an input stream and
use this stream to create a Scanner object as follows:
Scanner input = new Scanner(url.openStream());
• Now you can read the data from the input stream just like from
a local file.
Java URLConnection Class
• The Java URLConnection class represents a
communication link between the URL and the
application. It can be used to read and write data
to the specified resource referred by the URL
• URL has two components:
1. The protocol required to access the resource.
2. The location of the resource.
• Constractor:
• protected URLConnection(URL url) It constructs
a URL connection to the specified URL.
1. import java.io.*;
2. import java.net.*;
3. public class URLConnectionExample {
4. public static void main(String[] args){
5. try{
6. URL url=new URL("http:// www.google.com:80/index.htm
");
7. URLConnection urlcon=url.openConnection();
8. InputStream stream=urlcon.getInputStream();
9. int i;
10.while((i=stream.read())!=-1){
11.System.out.print((char)i);
12.}
13.}catch(Exception e){System.out.println(e);}
14.}
15.}
What is “Networking”
• What is “Networking”?
Getting two or more computers to send data to each
other
Having programs on separate computers interact with one
another
• Types of Networking
Client - Server
Many clients connect with one server.
Clients communicate only with server.
Peer-to-Peer
Clients connect to a group of other clients, with no server.
Clients communicating directly with each-other.
Client - Server Networking
• Advantages:
Easier to implement
Less coordination
involved
Easier to maintain
control of users
• Disadvantage:
Relies on one main
server for entire
operation
N-27
N-28
Sockets
• A socket is a connection on one computer used to
send data back and forth
• The application consists of multiple processes,
one running on each computer
• Sockets are created by the process on each computer
• The sockets then establish a connection to each other
One process sets up a server socket to receive a connection.
The other process sets up a client socket to establish
the connection with the server socket.
N-29
recv( )
send( )
close( ) close( )
controlled by
application process process
developer socket
socket
controlled by TCP with
TCP with
operating buffers, internet
system buffers,
variables
variables
N-30
Sockets in Java
• Found in java.net package
• java.net.ServerSocket
Accepts new incoming connections
Creates new ServerSocket for each connection
• java.net.Socket
Connects to an existing ServerSocket, through the
network
N-31
N-32
SocketClass:
•The java.net.Socket class is used to create a
socket so that both the client and the server can
communicate with each other easily. A socket is
an endpoint for communication between two
computers. The Socket class inherits the Object
class and implements the Closeable interface.
• Some commonly used public methods of the
Socket class are:
1. synchronized void close()
2. Socket (String host, int port) throws UnknownHostException, IOException
3. Socket()
4. OutputStream getOutputStream()
5. InputStream getInputStream()
java.net.Socket
• public Socket(String host, int port)
Throws IOException, UnknownHostException
Connects to a server socket at the provided address (host) on the provided
port
• public InputStream getInputStream()
Throws IOException
Returns the input stream from the socket
• public OutputStream getOutputStream()
Throws IOException
Returns the output stream from the socket
• public void close()
Throws IOException
Closes the connection
N-34
Server Socket Class
• The ServerSocket class represents a socket that
listens for connection requests from clients on a
specified port. When a connection is requested,
a Socket object is created to handle the
communication.
• Some Important methods of the ServerSocket
class are:
1. public Socket accept()
2. public synchronized void close()
java.net.ServerSocket
• public ServerSocket(int port)
Throws IOException
Creates a ServerSocket to accept new connections at the specified
port
N-36
Building a Network app
• This app will have one server and only one client
(no Threads needed)
• Build the server first
Need a new ServerSocket (int port)
The accept message to ServerSocket waits for a connection
that knows where the server is and what port it is listening
to
• aClientSocket.close();
Example:
Q3. Point out the problem in the following code. Does the code throw any exceptions?
Q1. What is wrong about creating a File object using the following statement?
new File("c:\book\test.dat");
new File("c:\\book\\test.dat");
new File("c:/book/test.dat");
Q2.what the function of following methods:
Q3.