Java Unit 5
Java Unit 5
EVENT HANDLING
DEFINITION
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
1
Steps to perform Event Handling
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
Example Program:
2
Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener
{
TextField tf;
AEvent(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);//passing current instance
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
public static void main(String args[])
{
new AEvent();
}
}
Output
MOUSE EVENTS
3
4
5
6
CHECKBOX
Definition
7
4. Checkbox(String label, boolean It constructs a checkbox with the given
state, CheckboxGroup group) label, set the given state in the specified
checkbox group.
o java.awt.Component
o java.lang.Object
8
checkbox is not selected.
Output
9
ToggleButton
Definition
Nested Classes
Modifier Class Description
and Type
Output
11
RADIOBUTTON
Definition
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
12
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
Output:
List View
Definition:
A list view is a scrollable list of items from which you can select desired items.
You can create a list view component by instantiating
the javafx.scene.control.ListView class. You can create either a vertical or a
horizontal ListView.
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
Example Program
13
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class ListViewExample extends Application
{
public void start(Stage stage)
{
Label label = new Label("Educational qualification:");
Font font = Font.font("verdana", FontWeight.BOLD,
FontPosture.REGULAR, 12);
label.setFont(font);
ObservableList<String> names =
FXCollections.observableArrayList("Engineering", "MCA", "MBA",
"Graduation", "MTECH", "Mphil", "Phd");
ListView<String> listView = new ListView<String>(names);
listView.setMaxSize(200, 160);
VBox layout = new VBox(10);
layout.setPadding(new Insets(5, 5, 5, 50));
layout.getChildren().addAll(label, listView);
layout.setStyle("-fx-background-color: BEIGE");
Scene scene = new Scene(layout, 595, 200);
stage.setTitle("List View Example");
stage.setScene(scene);
14
stage.show();
}
public static void main(String args[])
{
launch(args);
}
}
Output
COMBOBOX
Definition
A combo box is a combination of a text field and a drop-down list from which
the user can choose a value. If the text-field portion of the control is editable,
the user can enter a value in the field or edit a value retrieved from the drop-
down list.
15
Example:
Example Program
16
import javax.swing.*;
public class ComboBoxExample
{
JFrame f;
ComboBoxExample()
{
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args)
{
new ComboBoxExample();
}
}
Output
CHOICEBOX
Definition
ChoiceBox is a part of the JavaFX package.
ChoiceBox shows a set of items and allows the user to select a single
choice and it will show the currently selected item on the top.
ChoiceBox by default has no selected item unless otherwise selected.
17
Choice Class Declaration
Example Program:
import javafx.application.Application;
import javafx.scene.Scene;
18
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.collections.*;
import javafx.stage.Stage;
public class Choice_1 extends Application
{
Output
19
TEXTFIELD
Definition
TextField class is a part of JavaFX package.
It is a component that allows the user to enter a line of unformatted text,
it does not allow multi-line input it only allows the user to enter a single
line of text.
The text can then be used as per requirement.
setOnAction(EventHandler
value) Sets the value of the property onAction.
20
Example Program:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Textfield extends Application
{
public void start(Stage s)
{
s.setTitle("creating TextField");
TextField b = new TextField();
StackPane r = new StackPane();
r.getChildren().add(b);
Scene sc = new Scene(r, 200, 200);
s.setScene(sc);
s.show();
}
SCROLLPANE
Definition:
21
The ScrollPane allows the application to set the current, minimum, and
maximum values for positioning the contents in the horizontal and
vertical directions.
These values are mapped proportionally onto the layoutBounds of the
contained node.
Syntax
Step 2:
Syntax
scrollPane.setContent();
scrollPane.setVbarPolicy();
scrollPane.setHbarPolicy();
Step 3:
Create Tile Pane or any other display(like HBox or VBox etc. as per
requirement) class to add the items
Syntax:
Step 4:
Syntax:
22
Scene screen = new Scene(tPane, length, width);
Step 5:
Syntax:
stage.setScene(screen);
Step 6:
At last display output screen by showing stage reference with the show
() method.
Syntax:
stage.show();
Example Program of JavaFX ScrollPane:
package com.scrollpane;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ScrollPaneVerticlaScrollBar extends Application {
@Override
public void start(Stage primaryStage)
{
primaryStage.setTitle("ScrollPane Vertical");
ScrollPane scrollPane = new ScrollPane();
Label labelContent = new Label(
"EDUCBA is online teaching platform for IT courses like Java, HTML, CSS");
labelContent.setPrefSize(400, 100);
Label labelContent1 = new Label(
"EDUCBA is teach you every concept in simple and clear manner");
labelContent1.setPrefSize(400, 100);
Label labelContent2 = new Label(
23
"EDUCBA is offer you big discount for every course");
labelContent2.setPrefSize(400, 100);
VBox vBox=new VBox();
vBox.getChildren().add(labelContent);
vBox.getChildren().add(labelContent1);
vBox.getChildren().add(labelContent2);
scrollPane.setContent(vBox);
scrollPane.setVbarPolicy(ScrollBarPolicy.ALWAYS);
Scene scene = new Scene(scrollPane, 551, 201);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
Output:
24
LAYOUTS
Definition:
Layouts are the top level container classes that define the UI styles for
scene graph objects.
Layout can be seen as the parent node to all the other nodes.
JavaFX provides various layout panes that support different styles of
layouts.
In JavaFX, Layout defines the way in which the components are to be
seen on the stage.
It basically organizes the scene-graph nodes.
There are several built-in layout panes in JavaFX that are HBox, VBox,
StackPane, FlowBox, AnchorPane, etc.
Each Built-in layout is represented by a separate class which needs to be
instantiated in order to implement that particular layout pane.
All these classes belong to the javafx.scene.layout package.
javafx.scene.layout.Pane class is the base class for all the built-in layout
classes in JavaFX.
Layout Classes
Class Description
BorderPane Organizes nodes in top, left, right, centre and the bottom of the screen.
25
FlowPane Organizes the nodes in the horizontal rows according to the available
horizontal spaces. Wraps the nodes to the next line if the horizontal space
is less than the total width of the nodes
StackPane Organizes nodes in the form of a stack i.e. one onto another
1. Instantiate the respective layout class, for example, HBox root = new
HBox();
2. Setting the properties for the layout, for example, root.setSpacing(20);
3. Adding nodes to the layout object, for
example, root.getChildren().addAll(<NodeObjects>);
FLOWPANE
Definition:
FlowPane layout pane organizes the nodes in a flow that are wrapped at
the flowpane's boundary.
The horizontal flowpane arranges the nodes in a row and wrap them
according to the flowpane's width.
The vertical flowpane arranges the nodes in a column and wrap them
according to the flowpane's height.
FlowPane layout is represented by javafx.scene.layout.FlowPane class.
Property
Property Description Setter Methods
26
columnHalignmen The horizontal alignment of nodes setColumnHalignment(HPos
t within the columns. Value)
Constructors
1. FlowPane()
2. FlowPane(Double Hgap, Double Vgap)
3. FlowPane(Double Hgap, Double Vgap, Node? children)
4. FlowPane(Node... Children)
5. FlowPane(Orientation orientation)
6. FlowPane(Orientation orientation, double Hgap, Double Vgap)
7. FlowPane(Orientation orientation, double Hgap, Double Vgap, Node?
children )
8. FlowPane(Orientation orientation, Node... Children)
Example
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
27
{
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("FlowPane Example");
FlowPane root = new FlowPane();
root.setVgap(6);
root.setHgap(5);
root.setPrefWrapLength(250);
root.getChildren().add(new Button("Start"));
root.getChildren().add(new Button("Stop"));
root.getChildren().add(new Button("Reset"));
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
Output:
HBOX
Definition:
28
We just need to instantiate HBox class in order to create HBox layout.
Properties
The Properties of the class along with their setter methods are given in the table
below.
spacing This represents the space between the nodes in the setSpacing(Double)
HBox. It is of double type.
Constructors
The HBox class contains two constructors that are given below.
Example Program 1:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Label_Test extends Application
{
@Override
public void start(Stage primaryStage) throws Exception
{
29
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
HBox root = new HBox();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
Output:
Example Program 2:
Setting the space among the nodes.
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
30
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Label_Test extends Application
{
@Override
public void start(Stage primaryStage) throws Exception
{
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
HBox root = new HBox();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
root.setSpacing(40);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
Output
VBOX
Definition:
31
Properties
Constructors
1. VBox() : creates layout with 0 spacing
2. Vbox(Double spacing) : creates layout with a spacing value of double
type
3. Vbox(Double spacing, Node? children) : creates a layout with the
specified spacing among the specified child nodes
4. Vbox(Node? children) : creates a layout with the specified nodes having
0 spacing among them
Example
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Label_Test extends Application
{
@Override
public void start(Stage primaryStage) throws Exception
{
Button btn1 = new Button("Button 1");
32
Button btn2 = new Button("Button 2");
VBox root = new VBox();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
Output
BORDERPANE
Definition:
33
BorderPane arranges the nodes at the left, right, centre, top and bottom of
the screen.
It is represented by javafx.scene.layout.BorderPane class.
This class provides various methods like setRight(), setLeft(),
setCenter(), setBottom() and setTop() which are used to set the position
for the specified nodes.
We need to instantiate BorderPane class to create the BorderPane layout.
Properties
The properties of BorderPane class along with their setter methods are given in
the table below.
Node Bottom setBottom() Add the node to the bottom of the screen
Node Centre setCentre() Add the node to the centre of the screen
Node Left setLeft() Add the node to the left of the screen
Node Right setRight() Add the node to the right of the screen
Node Top setTop() Add the node to the top of the screen
Constructors
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
34
import javafx.stage.Stage;
public class Label_Test extends Application
{
@Override
public void start(Stage primaryStage) throws Exception
{
BorderPane BPane = new BorderPane();
BPane.setTop(new Label("This will be at the top"));
BPane.setLeft(new Label("This will be at the left"));
BPane.setRight(new Label("This will be at the Right"));
BPane.setCenter(new Label("This will be at the Centre"));
BPane.setBottom(new Label("This will be at the bottom"));
Scene scene = new Scene(BPane,600,400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
Output
STACKPANE
Definition:
The StackPane layout pane places all the nodes into a single stack where every
new node gets placed on the top of the previous node.
It is represented by javafx.scene.layout.StackPane class.
35
Then need to instantiate this class to implement StackPane layout into our
application.
Properties
The class contains only one property that is given below along with its setter
method.
Constructors
1. StackPane()
2. StackPane(Node? Children)
Example Program:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Label_Test extends Application
{
@Override
public void start(Stage primaryStage) throws Exception
{
Button btn1 = new Button("Button 1 on bottom ");
Button btn2 = new Button("Button 2 on top");
StackPane root = new StackPane();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
primaryStage.setScene(scene);
primaryStage.show();
36
}
public static void main(String[] args)
{
launch(args);
}
}
Output
GRIDPANE
Definition:
Properties
Property Description Setter Methods
37
Constructors
Example Program:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Label_Test extends Application
{
@Override
public void start(Stage primaryStage) throws Exception {
Label first_name=new Label("First Name");
Label last_name=new Label("Last Name");
TextField tf1=new TextField();
TextField tf2=new TextField();
Button Submit=new Button ("Submit");
GridPane root=new GridPane();
Scene scene = new Scene(root,400,200);
root.addRow(0, first_name,tf1);
root.addRow(1, last_name,tf2);
root.addRow(2, Submit);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
Output:
38
Menu
Definition:
Example Program:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MenuExample extends Application
{
public static void main(String[] args)
{
launch(args);
39
}
@Override
public void start(Stage primaryStage) throws Exception
{
BorderPane root = new BorderPane();
Scene scene = new Scene(root,200,300);
MenuBar menubar = new MenuBar();
Menu FileMenu = new Menu("File");
MenuItem filemenu1=new MenuItem("new");
MenuItem filemenu2=new MenuItem("Save");
MenuItem filemenu3=new MenuItem("Exit");
Menu EditMenu=new Menu("Edit");
MenuItem EditMenu1=new MenuItem("Cut");
MenuItem EditMenu2=new MenuItem("Copy");
MenuItem EditMenu3=new MenuItem("Paste");
EditMenu.getItems().addAll(EditMenu1,EditMenu2,EditMenu3);
root.setTop(menubar);
FileMenu.getItems().addAll(filemenu1,filemenu2,filemenu3);
menubar.getMenus().addAll(FileMenu,EditMenu);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Output
40
The object of JMenu class is a pull down menu component which is
displayed from the menu bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The
items used in a menu must belong to the JMenuItem or any of its
subclass.
41
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}
Output:
42