KEMBAR78
Java UNIT - 5 Material | PDF | Thread (Computing) | Process (Computing)
0% found this document useful (0 votes)
11 views30 pages

Java UNIT - 5 Material

Unit 5 covers string handling in Java, including string creation, manipulation methods, and the StringBuffer class for mutable strings. It also discusses multithreaded programming, emphasizing the need for multiple threads, thread lifecycle, and advantages of multithreading. Additionally, the unit introduces Java Database Connectivity and Java FX for GUI development.

Uploaded by

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

Java UNIT - 5 Material

Unit 5 covers string handling in Java, including string creation, manipulation methods, and the StringBuffer class for mutable strings. It also discusses multithreaded programming, emphasizing the need for multiple threads, thread lifecycle, and advantages of multithreading. Additionally, the unit introduces Java Database Connectivity and Java FX for GUI development.

Uploaded by

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

Object Oriented Programming Through Java UNIT-5

Object Oriented Programming Through Java

Unit - 5

UNIT V: String Handling in Java:Introduction, Interface Char Sequence, Class String, Methods
for Extracting Characters from Strings,Comparison, Modifying, Searching; Class String Buffer.
Multithreaded Programming:Introduction, Need for Multiple Threads Multithreaded
Programming for Multi-core Processor, Thread Class, Main Thread-Creation of New Threads,
Thread States, Thread Priority-Synchronization, Deadlock and Race Situations, Inter-thread
Communication - Suspending, Resuming, and Stopping of Threads.
Java Database Connectivity:Introduction, JDBC Architecture, Installing MySQL and MySQL
Connector/J, JDBC Environment Setup, Establishing JDBC Database Connections, ResultSet
Interface
Java FX GUI: Java FX Scene Builder, Java FX App Window Structure, displaying text and image,
event handling, laying out nodes in scene graph, mouse events

String Handling
• In Java, a string is a sequence of characters.
• Java implements strings as object of type String.
The String Constructors
String s = new String( );
default constructor
create an empty string
String s = new String(char chars[ ]);
create a string initialized by an array of characters
Example : char chars* + = ,‘a, ‘b’, ‘c’, ‘d’. ‘e’-;
String s = new String(chars);

String s = new String(char chars[ ], int startIndex, int numChars);


can specify a subrange of a character array as an initializer.
startIndex specifies the index at which the subrange begins.
numChars specifies the number of characters to use.
Example : char chars* + = ,‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’-
String s = new String(chars, 2, 3);

GATES-CSE(DS|CY) Page 1
Object Oriented Programming Through Java UNIT-5
-> initializes s with the characters ‘cde’
String s = new String(String strObj);
construct a String object that contains the same character sequence as another
String object using this constructor.
Example: char c* + = ,‘J’, ‘A’, ‘V’, ‘A’-;
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);

String s = new String(byte asciiChars[ ]);


Constructors that initialize a string when given a byte array.
asciiChars specifies the array of bytes.
String s = new String(byte asciiChars[ ],int startIndex, int numChars);
Example: byte ascii[ ] = {65, 66,67,68,69,70};
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2,3);
System.out.println(s2);
Output:
ABCDEF
CDE

String Length
• The length of the string is the number of characters it contains.
• To obtain this value, call the length( ) method.
int length( )
Example
char chars* + = ,‘a’, ‘b’, ‘c’-;
String s = new String(chars);
System.out.println(s.length( ));

GATES-CSE(DS|CY) Page 2
Object Oriented Programming Through Java UNIT-5
Special String Operations
• automatic creation of new string instances from string literals.
• concatenation of multiple String objects by use of the + operator.
• conversion of other data types to a String representation.
String Literals
• For each string literal in your program, Java automatically constructs a String object.
Example: String str = “abc”
• String literals can be used to call methods directly as if it were an object reference.
Example: System.out.println(“abc”.length( ));

String Concatenation
• Java does not allow operators to be applied to String objects.
• One exception is, the + operator, which concatenates two strings
producing a String object as the result.
• Example: String age = “9”;
String s = “He is” + age + “years old”;

System.out.println(s);String Concatenation with other data types


• Strings can be concatenated with other types of data.
• Example: int age = 9;
String s = “He is” + age + “years old”;
System.out.println(s);
• Mixing other types of operations with String concatenation expressions
String s = “four:” +2+2;
System.out.println(s); // output: four:22
• If 2 and 2 has to be added, then use the parenthesis
String s = “four:” +(2+2);
System.out.println(s); // output: four:4
__________________________________________________________________________
getChars( )
• To extract more than one character at a time.
• General form
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
sourceStart -> index of the beginning of the substring
sourceEnd -> index that is one past the end of the desired substring

GATES-CSE(DS|CY) Page 3
Object Oriented Programming Through Java UNIT-5
(from sourceStart to sourceEnd – 1)
target[ ] -> array that receive the characters specified.
targetStart -> index within target at which the substring will be copied• Example
class getCharsDemo
{
public static void main(String args[ ])
{
String s = “This is a Demo program”;
int start = 10, end =14;
char buf[ ] = new char[10];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}

String Comparison
equals( ) and equalsIgnoreCase( )
• To compare two strings for equality
boolean equals(String str)
• To perform a comparison that ignores case differences
boolean equalsIgnoreCase(String str)
str -> String object being compared with the invoking string object
returns -> true if the strings contain the same characters in the same order.

• Example
class EqualsDemo {
public static void main(String args[ ]) {
String s1 = “Hello”;
String s2 = “Hello”;
String s3 = “Hi”;
String s4 = “HELLO”;
System.out.println(s1.equals(s2);
System.out.println(s1.equals(s3);
System.out.println(s1.equals(s4);
System.out.println(s1.equalsIgnoreCase(s4);

GATES-CSE(DS|CY) Page 4
Object Oriented Programming Through Java UNIT-5
}
}

startsWith( ) and endsWith( )


• startsWith( ) -> determines whether a given string begins with a
specified string
• endsWith( ) -> determines whether the given string ends with a
specified string
• General forms:
boolean startsWith(String str)
boolean endsWith(String str)
• Example
“Foobar”.endsWith(“bar”) -> true
“Foobar”.startsWith(“Foo”) -> true
• Another form of startsWith( )
boolean startsWith(String str, int startIndex)
startIndex -> index into the invoking object at which point, the
search will begin
“Foobar”.startsWith(“bar”, 3) -> true

compareTo( )
• For sorting, we need to know which string is less than, equal to, or greater than the
next.
• A String is less than another if it comes before the other in dictionary order.
• A String is greater than another if it comes after the other in dictionary order.
• General form
int compareTo(String str)
str -> string being compared
Value Meaning
< 0 Invoking string less than str
> 0 Invoking string greater than str
= 0 Two strings are equal

GATES-CSE(DS|CY) Page 5
Object Oriented Programming Through Java UNIT-5
• Specifying starting points for the search
int indexOf(char ch, int startIndex)
int latIndexOf(char ch, int startIndex)
startIndex -> index at which point the search begins
-> for index( ) search runs from startIndex to the end of the string.
-> for lastIndexOf( ), search runs from startIndex to zero.• Example
String s = “This is a test.This is too”;
System.out.println(s.indexOf(‘t’));
System.out.println(s.lastIndexOf(‘t’));
System.out.println(s.indexOf(“is”);
System.out.println(s.indexOf(‘s’,10));
System.out.println(s.lastIndexOf(“is”, 15));

Changing the case of characters


• toLowerCase( ) -> converts all the characters in a String from uppercase
to lowercase
• toUpperCase( ) -> converts all the characters in a String from lowercase to
uppercase
• General forms
String toLowerCase( )
String toUpperCase( )• Example
String s = “This is a test”;
String upper = s.toUpperCase( );
String lower = s.toLowerCase( );
System.out.println(upper);
System.out.println(lower);
Output
THIS IS A TEST
this is a test

GATES-CSE(DS|CY) Page 6
Object Oriented Programming Through Java UNIT-5

5.2 StringBuffer class in Java


StringBuffer class
StringBuffer class is used to create a mutable string object. It represents growable and writable
character
sequence. As we know that String objects are immutable, so if we do a lot of changes with String
objects,
we will end up with a lot of memory leak.
So StringBuffer class is used when we have to make lot of modifications to our string. It is also
thread safe
i.e multiple threads cannot access it simultaneously. StringBuffer defines 4 constructors. They are,
1. StringBuffer ( )
2. StringBuffer ( int size )
3. StringBuffer ( String str )
4. StringBuffer ( charSequence [ ]ch )
StringBuffer() creates an empty string buffer and reserves room for 16 characters.
stringBuffer(int size) creates an empty string and takes an integer argument to set capacity of the
buffer.
Example showing difference between String and StringBuffer
class Test {
public static void main(String args[])
{
String str = "study";
str.concat("tonight");
System.out.println(str); // Output: study
StringBuffer strB = new StringBuffer("study");
strB.append("tonight");
System.out.println(strB); // Output: studytonight
}
}
Important methods of StringBuffer class
The following methods are some most commonly used methods of StringBuffer class.
append()
This method will concatenate the string representation of any type of data to the end of the
invoking

GATES-CSE(DS|CY) Page 7
Object Oriented Programming Through Java UNIT-5
StringBuffer object. append() method has several overloaded forms.
StringBuffer append(String str)
StringBuffer append(int n)StringBuffer append(Object obj)
The string representation of each parameter is appended to StringBuffer object.
StringBuffer str = new StringBuffer("test");
str.append(123);
System.out.println(str);
Output : test123
insert()
This method inserts one string into another. Here are few forms of insert() method.
StringBuffer insert(int index, String str)
StringBuffer insert(int index, int num)
StringBuffer insert(int index, Object obj)
Here the first parameter gives the index at which position the string will be inserted and string
representation
of second parameter is inserted into StringBuffer object.
StringBuffer str = new StringBuffer("test");
str.insert(4, 123);
System.out.println(str);
Output : test123
reverse()
This method reverses the characters within a StringBuffer object.
StringBuffer str = new StringBuffer("Hello");
str.reverse();
System.out.println(str);
Output : olleH
replace()
This method replaces the string from specified start index to the end index.
StringBuffer str = new StringBuffer("Hello World");
str.replace( 6, 11, "java");
System.out.println(str);Output : Hello java
capacity()
This method returns the current capacity of StringBuffer object.
StringBuffer str = new StringBuffer();
System.out.println( str.capacity() );

GATES-CSE(DS|CY) Page 8
Object Oriented Programming Through Java UNIT-5
Output : 16
ensureCapacity()
This method is used to ensure minimum capacity of StringBuffer object.
StringBuffer str = new StringBuffer("hello");
str.ensureCapacity(10);

Multithreaded Programming:Introduction, Need for Multiple Threads Multithreaded


Programming for Multi-core Processor, Thread Class, Main Thread-Creation of New Threads,
Thread States, Thread Priority-Synchronization, Deadlock and Race Situations, Inter-thread
Communication - Suspending, Resuming, and Stopping of Threads.

Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
o Each process has an address in memory. In other words, each process allocates a separate
memory area.
o A process is heavyweight.
o Cost of communication between the process is high.

GATES-CSE(DS|CY) Page 9
Object Oriented Programming Through Java UNIT-5
o Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.What is Thread in java A thread is a
lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS, and one process can have
multiple threads.
Note: At a time one thread is executed onlyJava Thread class
Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Life Cycle of a Thread
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. The following diagram shows the complete life cycle of a thread
Following are the stages of the life cycle –

GATES-CSE(DS|CY) Page 10
Object Oriented Programming Through Java UNIT-5
• New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
• Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another
thread to perform a task. A thread transitions back to the runnable state only when another thread
signals the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval expires or
when the event it is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or
otherwise terminates.Java Thread Methods
Method Description
1) void start() It is used to start the execution of the thread.
2) void run() It is used to do an action for a thread.
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing thread
object.

Thread implementation by extending the thread class


class A extends Thread {
public void run() {
for(int i=1;i<=5;i++) {
System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread {
public void run() {
for(int j=1;j<=5;j++) {
System.out.println("\t From ThreadB: j= "+j);
}
System.out.println("Exit from B");

GATES-CSE(DS|CY) Page 11
Object Oriented Programming Through Java UNIT-5
}
}
class C extends Thread {
public void run() {
for(int k=1;k<=5;k++) {
System.out.println("\t From ThreadC: k= "+k);
}
System.out.println("Exit from C");
}
}
class ThreadTest {
public static void main(String args[]) {
new A().start();
new B().start();
new C().start();
}
}

Accessing from shared resources:


If one thread tries to read the data and other thread tries to update the same data, it leads to
inconsistent state.
This can be prevented by synchronising access to data.
In Java: “Synchronized” method:
syncronised void update(){

}

Monitor shared object


class Account { // the 'monitor'
// DATA Members
int balance;
// if 'synchronized' is removed, the outcome is unpredictable
public synchronized void deposit( ) {
// METHOD BODY : balance += deposit_amount;

GATES-CSE(DS|CY) Page 12
Object Oriented Programming Through Java UNIT-5
}
public synchronized void withdraw( ) {
// METHOD BODY: balance -= deposit_amount;
}
public synchronized void enquire( ) {
// METHOD BODY: display balance.
}
}

Program with 3 threads and shared object


class MyThread implements Runnable {
Account account;
public MyThread (Account s) { account = s;}
public void run() { account.deposit(); }
} // end class MyThread
class YourThread implements Runnable { account
Account account;
public YourThread (Account s) { account = s; }
public void run() { account.withdraw(); }
} // end class YourThread
class HerThread implements Runnable {
Account account;
public HerThread (Account s) { account = s; }
public void run() {account.enquire(); }
} // end class HerThread

class InternetBankingSystem {
public static void main(String [] args ) {
Account obj= new Account ();
MyThread mt=new MyThread(obj);
YourThread yt=new MyThread(obj)
HerThread ht=new MyThread(obj)
Thread t1 = new Thread(mt);
Thread t2 = new Thread(yt);
Thread t3 = new Thread(ht);

GATES-CSE(DS|CY) Page 13
Object Oriented Programming Through Java UNIT-5
t1.start();
t2.start();
t3.start();
}
}

Thread Priority
◼ In Java, each thread is assigned priority, which affects the order in which it is scheduled
for running. The threads so far had same default priority (NORM_PRIORITY) and they
are served using FCFS policy.
◼ Java allows users to change priority:
◼ ThreadName.setPriority(intNumber)
◼ MIN_PRIORITY = 1
◼ NORM_PRIORITY=5
◼ MAX_PRIORITY=10
Example:
class A extends Thread {
public void run() {
System.out.println("Thread A started");
for(int i=1;i<=4;i++) {
System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread {
public void run() {
System.out.println("Thread B started");
for(int j=1;j<=4;j++){
System.out.println("\t From ThreadB: j= "+j);
} System.out.println("Exit from B");
}
}

class C extends Thread


{
public void run()
{
System.out.println("Thread C started");
for(int k=1;k<=4;k++)
{

GATES-CSE(DS|CY) Page 14
Object Oriented Programming Through Java UNIT-5
System.out.println("\t From ThreadC: k= "+k);
}
System.out.println("Exit from C");
}
}

class ThreadPriority
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);
System.out.println("Started Thread A");
threadA.start();
System.out.println("Started Thread B");
threadB.start();
System.out.println("Started Thread C");
threadC.start();
System.out.println("End of main thread");
}
}

GATES-CSE(DS|CY) Page 15
Object Oriented Programming Through Java UNIT-5
JavaFX UI Controls
This chapter provides an overview of the JavaFX UI controls available through the API.
The JavaFX UI controls are built by using nodes in the scene graph. Therefore, the controls can use
the visually rich features of the JavaFX platform. Because the JavaFX APIs are fully implemented
in Java, you can easily integrate the JavaFX UI controls into your existing Java applications.
Figure 1-1 shows the typical UI controls you can find in the Ensemble sample application. Try this
application to evaluate the wide range of controls, their behavior, and available styles.
Figure 1-1 JavaFX UI Controls

Supported UI Controls in JavaFX 2


The classes to construct UI controls reside in the javafx.scene.control package of the API.
The list of UI controls includes typical UI components that you might recognize from your previous
development of client applications in Java. However, the JavaFX 2 SDK introduces new Java UI
controls, like TitledPane, ColorPicker, and Pagination.
Figure 1-2 shows a screen capture of three TitledPane elements with lists of settings for a social
network application. The lists can slide in (retract) and slide out (extend).

GATES-CSE(DS|CY) Page 16
Object Oriented Programming Through Java UNIT-5
Figure 1-2 Titled Panes

Description of "Figure 1-2 Titled Panes"

2 Label
This chapter explains how to use the Label class that resides in the javafx.scene.control package of
the JavaFX API to display a text element. Learn how to wrap a text element to fit the specific space,
add a graphical image, or apply visual effects.
Figure 2-1 shows three common label usages. The label at the left is a text element with an image,
the label in the center represents rotated text, and the label at the right renders wrapped text.
Figure 2-1 Sample Application with Labels
Creating a Label
The JavaFX API provides three constructors of the Label class for creating labels in your
application, as shown in Example 2-1.
Example 2-1 Creating Labels
//An empty label
Label label1 = new Label();
//A label with the text element
Label label2 = new Label("Search");
//A label with the text element and graphical icon
Image image = new Image(getClass().getResourceAsStream("labels.jpg"));
Label label3 = new Label("Search", new ImageView(image));
Once you have created a label in your code, you can add textual and graphical content to it by using
the following methods of the Labeled class.
• The setText(String text) method – specifies the text caption for the label
• setGraphic(Node graphic)– specifies the graphical icon
The setTextFill method specifies the color to paint the text element of the label. Study Example 2-
2. It creates a text label, adds an icon to it, and specifies a fill color for the text.
Example 2-2 Adding an Icon and Text Fill to a Label
Label label1 = new Label("Search");

GATES-CSE(DS|CY) Page 17
Object Oriented Programming Through Java UNIT-5
Image image = new Image(getClass().getResourceAsStream("labels.jpg"));
label1.setGraphic(new ImageView(image));
label1.setTextFill(Color.web("#0076a3"));

3 Button
The Button class available through the JavaFX API enables developers to process an action when a
user clicks a button. The Button class is an extension of the Labeled class. It can display text, an
image, or both. Figure 3-1 shows buttons with various effects. In this chapter you will learn how to
create each of these button types.
Figure 3-1 Types of Buttons

Description of "Figure 3-1 Types of Buttons"


Creating a Button
You can create a Button control in a JavaFX application by using three constructors of the Button
class as shown on Example 3-1.
Example 3-1 Creating a Button
//A button with an empty text caption.
Button button1 = new Button();
//A button with the specified text caption.
Button button2 = new Button("Accept");
//A button with the specified text caption and icon.
Image imageOk = new Image(getClass().getResourceAsStream("ok.png"));
Button button3 = new Button("Accept", new ImageView(imageOk));
Because the Button class extends the Labeled class, you can use the following methods to specify
content for a button that does not have an icon or text caption:
• The setText(String text)method – specifies the text caption for the button
• The setGraphic(Node graphic)method – specifies the graphical icon
Example 3-2 shows how to create a button with an icon but without a text caption.
Example 3-2 Adding an Icon to a Button

GATES-CSE(DS|CY) Page 18
Object Oriented Programming Through Java UNIT-5
Image imageDecline = new Image(getClass().getResourceAsStream("not.png"));
Button button5 = new Button();
button5.setGraphic(new ImageView(imageDecline));
When added to the application, this code fragment produces the button shown in Figure 3-2.
Figure 3-2 Button with Icon

Description of "Figure 3-2 Button with Icon"

Assigning an Action
The primary function of each button is to produce an action when it is clicked. Use
the setOnAction method of the Button class to define what will happen when a user clicks the
button. Example 3-3 shows a code fragment that defines an action for button2.
Example 3-3 Defining an Action for a Button
button2.setOnAction(new EventHandler<ActionEvent>() {
Override public void handle(ActionEvent e) {
label.setText("Accepted");
}
});
ActionEvent is an event type that is processed by EventHandler. An EventHandler object provides
the handle method to process an action fired for a button. Example 3-3 shows how to override
the handle method, so that when a user presses button2 the text caption for a label is set to
"Accepted."
You can use the Button class to set as many event-handling methods as you need to cause the
specific behavior or apply visual effects.

Radio Button
This chapter discusses the radio button control and the RadioButton class, a specialized
implementation of the ToggleButton class.
A radio button control can be either selected or deselected. Typically radio buttons are combined
into a group where only one button at a time can be selected. This behavior distinguishes them
from toggle buttons, because all toggle buttons in a group can be in a deselected state.
Figure 4-1 shows three screen captures of the RadioButton sample, in which three radio buttons
are added to a group.

GATES-CSE(DS|CY) Page 19
Object Oriented Programming Through Java UNIT-5
Figure 4-1 RadioButton Sample

Description of "Figure 4-1 RadioButton Sample"


Study the following paragraphs to learn more about how to implement radio buttons in your
applications.
Creating a Radio Button
The RadioButton class available in the javafx.scene.control package of the JavaFX SDK provides
two constructors with which you can create a radio button. Example 4-1 shows two radio buttons.
The constructor with no parameters is used to create rb1. The text caption for this radio button is
set by using the setText method. The text caption for rb2 is defined within the corresponding
constructor.
Example 4-1 Creating Radio Buttons
//A radio button with an empty string for its label
RadioButton rb1 = new RadioButton();
//Setting a text label
rb1.setText("Home");
//A radio button with the specified label
RadioButton rb2 = new RadioButton("Calendar");
You can explicitly make a radio button selected by using the setSelected method and specifying
its value as true. If you need to check whether a particular radio button was selected by a user,
apply the isSelected method.
Because the RadioButton class is an extension of the Labeled class, you can specify not only a
text caption, but also an image. Use the setGraphic method to specify an image. Example 4-
2 demonstrates how to implement a graphical radio button in your application.
Example 4-2 Creating a Graphical Radio Button
Image image = new Image(getClass().getResourceAsStream("ok.jpg"));
RadioButton rb = new RadioButton("Agree");
rb.setGraphic(new ImageView(image));
Adding Radio Buttons to Groups
Radio buttons are typically used in a group to present several mutually exclusive options.
The ToggleGroup object provides references to all radio buttons that are associated with it and
manages them so that only one of the radio buttons can be selected at a time. Example 4-3 creates

GATES-CSE(DS|CY) Page 20
Object Oriented Programming Through Java UNIT-5
a toggle group, creates three radio buttons, adds each radio button to the toggle group, and
specifies which button should be selected when the application starts.
Example 4-3 Creating a Group of Radio Buttons
final ToggleGroup group = new ToggleGroup();

RadioButton rb1 = new RadioButton("Home");


rb1.setToggleGroup(group);
rb1.setSelected(true);

RadioButton rb2 = new RadioButton("Calendar");


rb2.setToggleGroup(group);

RadioButton rb3 = new RadioButton("Contacts");


rb3.setToggleGroup(group);
When these radio buttons are laid out by using the layout containers and added to the content of
the application, the output should resemble Figure 4-2.
Figure 4-2 Three Radio Buttons Combined in a Group

Description of "Figure 4-2 Three Radio Buttons Combined in a Group

Processing Events for Radio Buttons


Typically, the application performs an action when one of the radio buttons in the group is
selected. Review the code fragment in Example 4-4 to learn how to change an icon according to
which radio button is selected.
Example 4-4 Processing Action for Radio Buttons
ImageView image = new ImageView();

rb1.setUserData("Home")
rb2.setUserData("Calendar");
rb3.setUserData("Contacts");

final ToggleGroup group = new ToggleGroup();


group.selectedToggleProperty().addListener(new ChangeListener<Toggle>(){

GATES-CSE(DS|CY) Page 21
Object Oriented Programming Through Java UNIT-5
public void changed(ObservableValue<? extends Toggle> ov,
Toggle old_toggle, Toggle new_toggle) {
if (group.getSelectedToggle() != null) {
final Image image = new Image(
getClass().getResourceAsStream(
group.getSelectedToggle().getUserData().toString() +
".jpg"
)
);
icon.setImage(image);
}
}
});

Checkbox
This chapter teaches how to add checkboxes to your JavaFX applications.
Although checkboxes look similar to radio buttons, they cannot be combined into toggle groups to
enable the selection of many options at one time. See the Radio Button and Toggle Button
chapters for more information.
Figure 6-1 shows a screen capture of an application in which three checkboxes are used to enable
or disable icons in an application toolbar.
Figure 6-1 Checkbox Sample

Description of "Figure 6-1 Checkbox Sample"


Creating Checkboxes
Example 6-1 creates two simple checkboxes.
Example 6-1 Creating Checkboxes
//A checkbox without a caption
CheckBox cb1 = new CheckBox();
//A checkbox with a string caption
CheckBox cb2 = new CheckBox("Second");

GATES-CSE(DS|CY) Page 22
Object Oriented Programming Through Java UNIT-5

cb1.setText("First");
cb1.setSelected(true);
Once you have created a checkbox, you can modify it by using methods available through the
JavaFX APIs. In Example 6-1 the setText method defines the text caption of the c1 checkbox.
The setSelected method is set to true so that the cb1 checkbox is selected when the application is
started.
Defining a State
The checkbox can be either defined or undefined. When it is defined, you can select or deselect it.
However, when the checkbox is undefined, it cannot be selected or deselected. Use a combination
of the setSelected and setIndeterminate methods of the CheckBox class to specify the state of the
checkbox. Table 6-1 shows three states of a checkbox based on
its INDETERMINATE and SELECTED properties.
Table 6-1 States of a Checkbox
Property Values Checkbox Appearance

INDETERMINATE = false
SELECTED = false

INDETERMINATE =false
SELECTED = true

INDETERMINATE = true
SELECTED = true/false

You might need enabling three states for checkboxes in your application when they represent UI
elements that can be in mixed states, for example, "Yes", "No", "Not Applicable."
The allowIndeterminate property of the CheckBox object determines whether the checkbox
should cycle through all three states: selected, deselected, and undefined. If the variable is true,
the control will cycle through all the three states. If it is false, the control will cycle through the
selected and deselected states. The application described in the next section constructs three
checkboxes and enables only two states for them.
Setting the Behavior
The code fragment in Example 6-2 creates three checkboxes, such that if a checkbox is selected,
the corresponding icon appears in a toolbar.

GATES-CSE(DS|CY) Page 23
Object Oriented Programming Through Java UNIT-5
Example 6-2 Setting the Behavior for the Checkboxes
final String[] names = new String[]{"Security", "Project", "Chart"};
final Image[] images = new Image[names.length];
final ImageView[] icons = new ImageView[names.length];
final CheckBox[] cbs = new CheckBox[names.length];

for (int i = 0; i < names.length; i++) {


final Image image = images[i] =
new Image(getClass().getResourceAsStream(names[i] + ".png"));
final ImageView icon = icons[i] = new ImageView();
final CheckBox cb = cbs[i] = new CheckBox(names[i]);
cb.selectedProperty().addListener(new ChangeListener<Boolean>() {
public void changed(ObservableValue<? extends Boolean> ov,
Boolean old_val, Boolean new_val) {
icon.setImage(new_val ? image : null);
}
});
}

*** Note also refer Lab experiments *****

Events in JavaFX
JavaFX provides support to handle a wide varieties of events. The class named Event of the
package javafx.event is the base class for an event.
An instance of any of its subclass is an event. JavaFX provides a wide variety of events. Some of
them are are listed below.
• Mouse Event − This is an input event that occurs when a mouse is clicked. It is
represented by the class named MouseEvent. It includes actions like mouse clicked,
mouse pressed, mouse released, mouse moved, mouse entered target, mouse exited target,
etc.
• Key Event − This is an input event that indicates the key stroke occurred on a node. It is
represented by the class named KeyEvent. This event includes actions like key pressed,
key released and key typed.

GATES-CSE(DS|CY) Page 24
Object Oriented Programming Through Java UNIT-5
• Drag Event − This is an input event which occurs when the mouse is dragged. It is
represented by the class named DragEvent. It includes actions like drag entered, drag
dropped, drag entered target, drag exited target, drag over, etc.
• Window Event − This is an event related to window showing/hiding actions. It is
represented by the class named WindowEvent. It includes actions like window hiding,
window shown, window hidden, window showing, etc.

Above image is the event dispatch chain for the event generated, when we click on the play button
in the above scenario.
Using Convenience Methods for Event Handling
Some of the classes in JavaFX define event handler properties. By setting the values to these
properties using their respective setter methods, you can register to an event handler. These
methods are known as convenience methods.
Most of these methods exist in the classes like Node, Scene, Window, etc., and they are available
to all their sub classes. Following table describes various convenience methods that can be used
on different events:

User Action Event Type EventHandler Properties

onKeypressed
Pressing, releasing, or
KeyEvent onKeyReleased
typing a key on keyboard.
onKeyTyped

GATES-CSE(DS|CY) Page 25
Object Oriented Programming Through Java UNIT-5

onMouseClicked
onMouseMoved
Moving, Clicking, or onMousePressed
MouseEvent
dragging the mouse. onMouseReleased
onMouseEntered
onMouseExited

onMouseDragged
onMouseDragEntered
Pressing, Dragging, and
onMouseDragExited
Releasing of the mouse MouseDragEvent
onMouseDragged
button.
onMouseDragOver
onMouseDragReleased

Generating, Changing,
Removing or Committing
InputMethodEvent onInputMethodTextChanged
input from an alternate
method.

onDragDetected
onDragDone
Performing Drag and Drop
onDragDropped
actions supported by the DragEvent
onDragEntered
platform.
onDragExited
onDragOver

onScroll
Scrolling an object. ScrollEvent onScrollStarted
onScrollFinished

onRotate
Rotating an object. RotateEvent onRotationFinished
onRotationStarted

GATES-CSE(DS|CY) Page 26
Object Oriented Programming Through Java UNIT-5

onSwipeUP
Swiping an object upwards,
onSwipeDown
downwards, to the right and SwipeEvent
onSwipeLeft
left.
onSwipeRight

onTouchMoved
Touching an object. TouchEvent onTouchReleased
onTouchStationary

onZoom
Zooming on an object. ZoomEvent onZoomStarted
onZoomFinished

Requesting Context Menu. ContextMenuEvent onContextMenuRequested

Pressing a button, showing


or hiding a combo box, ActionEvent
selecting a menu item.

Editing an item in a list. ListView.EditEvent

Editing an item in a table. TableColumn.CellEditEvent

Editing an item in a tree. TreeView.EditEvent

Encountering an error in a
MediaErrorEvent
media player.

Showing or Hiding Menu. Event

Hiding a pop-up window. Event

Selecting or Closing a Tab. Event

Showing, Minimizing, or
WindowEvent
Closing a Window.

Syntax
Following is the format of Convenience methods used for registering event handlers:
setOnEvent-type(EventHandler<? super event-class> value)

GATES-CSE(DS|CY) Page 27
Object Oriented Programming Through Java UNIT-5
For example, to add a mouse event listener to a button, you can use the convenience
method setOnMouseClicked() as shown below.
playButton.setOnMouseClicked((new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
System.out.println("Hello World");
pathTransition.play();
}
}));

Example

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ConvenienceMethodsExample extends Application
{
Override public void start(Stage stage)
{
//Drawing a Circle Circle circle = new Circle();
//Setting the position of the circle circle.setCenterX(300.0f); circle.setCenterY(135.0f);
//Setting the radius of the circle circle.setRadius(25.0f);
//Setting the color of the circle circle.setFill(Color.BROWN);
//Setting the stroke width of the circle circle.setStrokeWidth(20);
//Creating a Path Path path = new Path();

GATES-CSE(DS|CY) Page 28
Object Oriented Programming Through Java UNIT-5
//Moving to the staring point
MoveTo moveTo = new MoveTo(208, 71);
//Creating 1st line
LineTo line1 = new LineTo(421, 161);
//Creating 2nd line
LineTo line2 = new LineTo(226,232);
//Creating 3rd line
LineTo line3 = new LineTo(332,52);
//Creating 4th line
LineTo line4 = new LineTo(369, 250);
//Creating 5th line
LineTo line5 = new LineTo(208, 71);
//Adding all the elements to the path path.getElements().add(moveTo);
path.getElements().addAll(line1, line2, line3, line4, line5);
//Creating the path transition PathTransition pathTransition = new PathTransition();
//Setting the duration of the transition pathTransition.setDuration(Duration.millis(1000));
//Setting the node for the transition pathTransition.setNode(circle);
//Setting the path for the transition
pathTransition.setPath(path);
//Setting the orientation of the path
pathTransition.setOrientation( PathTransition.OrientationType.ORTHOGONAL_TO_TAN
GENT);
//Setting the cycle count for the transition
pathTransition.setCycleCount(50);
//Setting auto reverse value to true
pathTransition.setAutoReverse(false);
//Creating play button
Button playButton = new Button("Play");
playButton.setLayoutX(300);
playButton.setLayoutY(250);
circle.setOnMouseClicked (new EventHandler<javafx.scene.input.MouseEvent>() {
Override public void handle(javafx.scene.input.MouseEvent e) {
System.out.println("Hello World"); circle.setFill(Color.DARKSLATEBLUE); } });
playButton.setOnMouseClicked((new EventHandler<MouseEvent>() {

GATES-CSE(DS|CY) Page 29
Object Oriented Programming Through Java UNIT-5
public void handle(MouseEvent event) { System.out.println("Hello World");
pathTransition.play(); } }));
//Creating stop button
Button stopButton = new Button("stop");
stopButton.setLayoutX(250);
stopButton.setLayoutY(250);
stopButton.setOnMouseClicked((new EventHandler<MouseEvent>() { public void
handle(MouseEvent event) { System.out.println("Hello World"); pathTransition.stop(); } }));
//Creating a Group object
Group root = new Group(circle, playButton, stopButton);
//Creating a scene object
Scene scene = new Scene(root, 600, 300); scene.setFill(Color.LAVENDER);
//Setting title to the
Stage stage.setTitle("Convenience Methods Example");
//Adding scene to the stage stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[])
{
launch(args);
}
}

GATES-CSE(DS|CY) Page 30

You might also like