0% found this document useful (0 votes)
9 views8 pages

OOPS UNIT - V Notes

The document covers Unit V of the CS3391 Object-Oriented Programming course, focusing on event handling, controls, and components in JavaFX. It explains the types of events, event handling mechanisms, and provides examples of GUI components and event handling code. Additionally, it includes practical examples of creating a login page and a registration form using various JavaFX controls.
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)
9 views8 pages

OOPS UNIT - V Notes

The document covers Unit V of the CS3391 Object-Oriented Programming course, focusing on event handling, controls, and components in JavaFX. It explains the types of events, event handling mechanisms, and provides examples of GUI components and event handling code. Additionally, it includes practical examples of creating a login page and a registration form using various JavaFX controls.
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/ 8

CS3391 – OBJECT ORIENTED PROGRAMMING

KINGS ENGINEERING COLLEGE


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CS3391 – OBJECT ORIENTED PROGRAMMING
UNIT V – EVENT HANDLING, CONTROLS AND COMPONENETS
JAVAFX Events and Controls: Event Basics – Handling Key and Mouse Events. Controls:
Checkbox, ToggleButton – RadioButtons – ListView – ComboBox – ChoiceBox – Text Controls –
ScrollPane. Layouts – FlowPane – HBox and VBox – BorderPane – StackPane – GridPane. Menus –
Basics – Menu – Menu bars – MenuItem.
JAVAFX Events and Controls
Event:
In JavaFX, we can develop GUI applications, web applications and graphical applications. In such
applications, whenever a user interacts with the application (nodes), an event is said to have been occurred.
Example: clicking on a button, moving the mouse, entering a character through keyboard, selecting an
item from list, scrolling the page are the activities that causes an event to happen.
Types of Events
 Foreground Events
Those events which require the direct interaction of a user known as foreground events.
They are generated as consequences of a person interacting with the graphical components in a
Graphical User Interface.
Example: clicking on a button, moving the mouse, entering a character through keyboard, selecting
an item from list, scrolling the page, etc.
 Background Events
Those events that don't require the interaction of end-user are known as background events.
The operating system interruptions, hardware or software failure, timer expiry, operation
completion are the example of background events.
Events in JavaFX
JavaFX provides support to handle 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.
 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.
Event Handling
Event Handling is the mechanism that controls the event and decides what should happen, if an event
occurs. This mechanism has the code which is known as an event handler that is executed when an event
occurs.
JavaFX provides handlers and filters to handle events. In JavaFX every event has −
Target − The node on which an event occurred. A target can be a window, scene, and a node.
Source − The source from which the event is generated will be the source of the event. In the above
scenario, mouse is the source of the event.

K.G.SARAVANAN \ ASST. PROF.\ IT DEPT 1 II IT


CS3391 – OBJECT ORIENTED PROGRAMMING
Type − Type of the occurred event; in case of mouse event – mouse pressed, mouse released are the type
of events.
Assume that we have an application which has a Circle, Stop and Play Buttons inserted using a group
object as follows −

If you click on the play button, the source will be the mouse, the target node will be the play button and
the type of the event generated is the mouse click.

Phases of Event Handling in JavaFX


i)Route Construction
Whenever an event is generated, the default/initial route of the event is determined by construction of
an Event Dispatch chain. It is the path from the stage to the source Node.
Following is the event dispatch chain for the event generated, when we click on the play button in the
above scenario.

ii)Event Capturing Phase


After the construction of the event dispatch chain, the root node of the application dispatches the event.
This event travels to all nodes in the dispatch chain (from top to bottom). If any of these nodes has
a filter registered for the generated event, it will be executed. If none of the nodes in the dispatch chain
has a filter for the event generated, then it is passed to the target node and finally the target node processes
the event.
iii)Event Bubbling Phase
In the event bubbling phase, the event is travelled from the target node to the stage node (bottom to top). If
any of the nodes in the event dispatch chain has a handler registered for the generated event, it will be
executed. If none of these nodes have handlers to handle the event, then the event reaches the root node
and finally the process will be completed.

K.G.SARAVANAN \ ASST. PROF.\ IT DEPT 2 II IT


CS3391 – OBJECT ORIENTED PROGRAMMING
iv)Event Handlers and Filters
Event filters and handlers are those which contains application logic to process an event. A node can
register to more than one handler/filter. In case of parent–child nodes, you can provide a common
filter/handler to the parents, which is processed as default for all the child nodes.
As mentioned above, during the event, processing is a filter that is executed and during the event bubbling
phase, a handler is executed. All the handlers and filters implement the interface EventHandler of the
package javafx.event.
Event Handling Example
Following is an example demonstrating the event handling in JavaFX using the event filters. Save this
code in a file with name EventFiltersExample.java.
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.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;

import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class EventFiltersExample extends Application {


@Override
public void start(Stage stage) {
Circle circle = new Circle(); //Drawing a Circle
circle.setCenterX(300.0f); //Setting the position of the circle
circle.setCenterY(135.0f);
circle.setRadius(25.0f); //Setting the radius of the circle
circle.setFill(Color.BROWN); //Setting the color of the circle
circle.setStrokeWidth(20); //Setting the stroke width of the circle
Text text = new Text("Click on the circle to change its color"); //Setting the text
text.setFont(Font.font(null, FontWeight.BOLD, 15)); //Setting the font of the text
text.setFill(Color.CRIMSON); //Setting the color of the text
text.setX(150); //setting the position of the text
text.setY(50);
EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() //Creating the mouse
event handler
{ @Override
public void handle(MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
};
//Registering the event filter
circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);
Group root = new Group(circle, text); //Creating a Group object
Scene scene = new Scene(root, 600, 300); //Creating a scene object
scene.setFill(Color.LAVENDER); //Setting the fill color to the scene
stage.setTitle("Event Filters Example"); //Setting title to the Stage

K.G.SARAVANAN \ ASST. PROF.\ IT DEPT 3 II IT


CS3391 – OBJECT ORIENTED PROGRAMMING
stage.setScene(scene); //Adding scene to the stage
stage.show(); //Displaying the contents of the stage
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac EventFiltersExample.java
java EventFiltersExample

On executing, the above program generates a JavaFX window as shown below.

Every user interface considers the following three main aspects −


 UI elements − These are the core visual elements which the user eventually sees and interacts with.
JavaFX provides a huge list of widely used and common elements varying from basic to complex,
which we will cover in this tutorial.
 Layouts − They define how UI elements should be organized on the screen and provide a final
look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter.
 Behavior − These are events which occur when the user interacts with UI elements. This part will
be covered in the Event Handling chapter.
JavaFX provides several classes in the package javafx.scene.control. To create various GUI components
(controls), JavaFX supports several controls such as date picker, button text field, etc.
Each control is represented by a class; you can create a control by instantiating its respective class.
Following is the list of commonly used controls while the GUI is designed using JavaFX.

S.No Control & Description

1 Label A Label object is a component for placing text.

2 Button This class creates a labeled button.

3 ColorPicker A ColorPicker provides a pane of controls designed to allow a user to


manipulate and select a color.

4 CheckBox A CheckBox is a graphical component that can be in either an on(true) or off


(false) state.

5 RadioButton The RadioButton class is a graphical component, which can either be in a ON


(true) or OFF (false) state in a group.

6 ListView A ListView component presents the user with a scrolling list of text items.

7 TextField A TextField object is a text component that allows for the editing of a single line of text.
K.G.SARAVANAN \ ASST. PROF.\ IT DEPT 4 II IT
CS3391 – OBJECT ORIENTED PROGRAMMING
8 PasswordField A PasswordField object is a text component specialized for password entry.

9 Scrollbar A Scrollbar control represents a scroll bar component in order to enable user to
select from range of values.

10 FileChooser A FileChooser control represents a dialog window from which the user can
select a file.

11 ProgressBar As the task progresses towards completion, the progress bar displays the task's
percentage of completion.

12 Slider A Slider lets the user graphically select a value by sliding a knob within a bounded
interval.
Example
The following program is an example which displays a login page in JavaFX. Here, we are using the controls label,
text field, password field and button. Save this code in a file with the name LoginPage.java.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.geometry.Pos;

import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class LoginPage extends Application {


@Override
public void start(Stage stage) {

Text text1 = new Text("Email"); //creating label email


Text text2 = new Text("Password"); //creating label password
TextField textField1 = new TextField(); //Creating Text Filed for email
PasswordField textField2 = new PasswordField(); //Creating Text Filed for password
Button button1 = new Button("Submit"); //Creating Buttons
Button button2 = new Button("Clear");
GridPane gridPane = new GridPane(); //Creating a Grid Pane
gridPane.setMinSize(400, 200); //Setting size for the pane
gridPane.setPadding(new Insets(10, 10, 10, 10)); //Setting the padding
gridPane.setVgap(5); //Setting the vertical and horizontal gaps between the columns
gridPane.setHgap(5);
gridPane.setAlignment(Pos.CENTER); //Setting the Grid alignment
//Arranging all the nodes in the grid
gridPane.add(text1, 0, 0);
gridPane.add(textField1, 1, 0);
gridPane.add(text2, 0, 1);
gridPane.add(textField2, 1, 1);
gridPane.add(button1, 0, 2);
gridPane.add(button2, 1, 2);
button1.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;"); //Styling nodes
button2.setStyle("-fx-background-color: darkslateblue; -fx-text-fill: white;");
text1.setStyle("-fx-font: normal bold 20px 'serif' ");
K.G.SARAVANAN \ ASST. PROF.\ IT DEPT 5 II IT
CS3391 – OBJECT ORIENTED PROGRAMMING
text2.setStyle("-fx-font: normal bold 20px 'serif' ");
gridPane.setStyle("-fx-background-color: BEIGE;");
Scene scene = new Scene(gridPane); //Creating a scene object
stage.setTitle("CSS Example"); //Setting title to the Stage
stage.setScene(scene); //Adding scene to the stage
stage.show();//Displaying the contents of the stage
}
public static void main(String args[]){
launch(args);
}
}
Output:

The following program is an example of a registration form, which demonstrates controls in JavaFX such
as Date Picker, Radio Button, Toggle Button, Check Box, List View, Choice List, etc.
Save this code in a file with the name Registration.java.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import javafx.geometry.Insets;
import javafx.geometry.Pos;

import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.ToggleButton;
import javafx.stage.Stage;

public class Registration extends Application {


@Override
public void start(Stage stage) {

Text nameLabel = new Text("Name"); //Label for name


TextField nameText = new TextField();//Text field for name
Text dobLabel = new Text("Date of birth"); //Label for date of birth
DatePicker datePicker = new DatePicker();//date picker to choose date
Text genderLabel = new Text("gender"); //Label for gender
K.G.SARAVANAN \ ASST. PROF.\ IT DEPT 6 II IT
CS3391 – OBJECT ORIENTED PROGRAMMING

ToggleGroup groupGender = new ToggleGroup(); //Toggle group of radio buttons


RadioButton maleRadio = new RadioButton("male");
maleRadio.setToggleGroup(groupGender);
RadioButton femaleRadio = new RadioButton("female");
femaleRadio.setToggleGroup(groupGender);

Text reservationLabel = new Text("Reservation"); //Label for reservation

//Toggle button for reservation


ToggleButton Reservation = new ToggleButton();
ToggleButton yes = new ToggleButton("Yes");
ToggleButton no = new ToggleButton("No");
ToggleGroup groupReservation = new ToggleGroup();
yes.setToggleGroup(groupReservation);
no.setToggleGroup(groupReservation);

Text technologiesLabel = new Text("Technologies Known"); //Label for technologies known


CheckBox javaCheckBox = new CheckBox("Java"); //check box for education
javaCheckBox.setIndeterminate(false);

CheckBox dotnetCheckBox = new CheckBox("DotNet"); //check box for education


javaCheckBox.setIndeterminate(false);

Text educationLabel = new Text("Educational qualification"); //Label for education


//list View for educational qualification
ObservableList<String> names = FXCollections.observableArrayList(
"Engineering", "MCA", "MBA", "Graduation", "MTECH", "Mphil", "Phd");
ListView<String> educationListView = new ListView<String>(names);

Text locationLabel = new Text("location"); //Label for location


//Choice box for location
ChoiceBox locationchoiceBox = new ChoiceBox();
locationchoiceBox.getItems().addAll
("Hyderabad", "Chennai", "Delhi", "Mumbai", "Vishakhapatnam");
Button buttonRegister = new Button("Register"); //Label for register
GridPane gridPane = new GridPane(); //Creating a Grid Pane
gridPane.setMinSize(500, 500); //Setting size for the pane
gridPane.setPadding(new Insets(10, 10, 10, 10)); //Setting the padding
//Setting the vertical and horizontal gaps between the columns
gridPane.setVgap(5);
gridPane.setHgap(5);
gridPane.setAlignment(Pos.CENTER); //Setting the Grid alignment

//Arranging all the nodes in the grid


gridPane.add(nameLabel, 0, 0);
gridPane.add(nameText, 1, 0);
gridPane.add(dobLabel, 0, 1);
gridPane.add(datePicker, 1, 1);
gridPane.add(genderLabel, 0, 2);
gridPane.add(maleRadio, 1, 2);
gridPane.add(femaleRadio, 2, 2);
gridPane.add(reservationLabel, 0, 3);
gridPane.add(yes, 1, 3);
gridPane.add(no, 2, 3);
gridPane.add(technologiesLabel, 0, 4);
K.G.SARAVANAN \ ASST. PROF.\ IT DEPT 7 II IT
CS3391 – OBJECT ORIENTED PROGRAMMING
gridPane.add(javaCheckBox, 1, 4);
gridPane.add(dotnetCheckBox, 2, 4);
gridPane.add(educationLabel, 0, 5);
gridPane.add(educationListView, 1, 5);
gridPane.add(locationLabel, 0, 6);
gridPane.add(locationchoiceBox, 1, 6);
gridPane.add(buttonRegister, 2, 8);
buttonRegister.setStyle( "-fx-background-color: darkslateblue; -fx-textfill: white;"); //Styling nodes
nameLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
dobLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
genderLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
reservationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
technologiesLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
educationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
locationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
gridPane.setStyle("-fx-background-color: BEIGE;"); //Setting the back ground color
Scene scene = new Scene(gridPane); //Creating a scene object
stage.setTitle("Registration Form"); //Setting title to the Stage
stage.setScene(scene); //Adding scene to the stage
stage.show(); //Displaying the contents of the stage
}
public static void main(String args[]){
launch(args);
}
}
Output:

********************************** ALL THE BEST ************************************

K.G.SARAVANAN \ ASST. PROF.\ IT DEPT 8 II IT

You might also like