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

Java Unit 5

Uploaded by

sowmyaprema249
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java Unit 5

Uploaded by

sowmyaprema249
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

UNIT-5

JAVAFX EVENT HANDLING, CONTROLS AND COMPONENTS

EVENT HANDLING

DEFINITION

 Changing the state of an object is known as an event. For example, click


on button, dragging mouse etc.
 The java.awt.event package provides many event classes and Listener
interfaces for event handling.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

1
Steps to perform Event Handling

Following steps are required to perform event handling:

1. Register the component with the Listener

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){}

Java Event Handling Code

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

The Checkbox class is used to create a checkbox. It is used to turn an option on


(true) or off (false). Clicking on a Checkbox changes its state from "on" to "off"
or from "off" to "on".
AWT Checkbox Class Declaration
public class Checkbox extends Component implements ItemSelectable, Accessibl
e

Checkbox Class Constructors

Sr. Constructor Description


no.

1. Checkbox() It constructs a checkbox with no string as the


label.

2. Checkbox(String label) It constructs a checkbox with the given


label.

3. Checkbox(String label, boolean It constructs a checkbox with the given label


state) and sets the given state.

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.

5. Checkbox(String label, It constructs a checkbox with the given


CheckboxGroup group, boolean label, in the given checkbox group and set to
state) the specified state.

Method inherited by Checkbox

The methods of Checkbox class are inherited by following classes:

o java.awt.Component
o java.lang.Object

Checkbox Class Methods

Sr. Method name Description


no.

1. void addItemListener(ItemListener It adds the given item listener to get


IL) the item events from the checkbox.

2. AccessibleContext It fetches the accessible context of


getAccessibleContext() checkbox.

3. void addNotify() It creates the peer of checkbox.

4. CheckboxGroup It determines the group of checkbox.


getCheckboxGroup()

5. ItemListener[] getItemListeners() It returns an array of the item


listeners registered on checkbox.

6. String getLabel() It fetched the label of checkbox.

7. T[] It returns an array of all the objects


getListeners(Class listenerType) registered as FooListeners.

8. Object[] getSelectedObjects() It returns an array (size 1) containing


checkbox label and returns null if

8
checkbox is not selected.

9. boolean getState() It returns true if the checkbox is on,


else returns off.

10. protected String paramString() It returns a string representing the


state of checkbox.

Checkbox Example Program:


import java.awt.*;
public class CheckboxExample1
{
CheckboxExample1()
{
Frame f = new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100, 150, 50, 50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main (String args[])
{
new CheckboxExample1();
}
}

Output

9
ToggleButton

Definition

ToggleButton is used to create toggle button, it is two-states button to switch on


or off.

Nested Classes
Modifier Class Description
and Type

protected JToggleButton.AccessibleJToggleButto This class implements


class n accessibility support for the
JToggleButton class.

static class JToggleButton.ToggleButtonModel The ToggleButton model

ToggleButton Example Program


import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;

public class JToggleButtonExample extends JFrame implements ItemListener


{
10
public static void main(String[] args)
{
new JToggleButtonExample();
}
private JToggleButton button;
JToggleButtonExample()
{
setTitle("JToggleButton with ItemListener Example");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setJToggleButton()
{
button = new JToggleButton("ON");
add(button);
}
private void setAction()
{
button.addItemListener(this);
}
public void itemStateChanged(ItemEvent eve)
{
if (button.isSelected())
button.setText("OFF");
else
button.setText("ON");
}
}

Output

11
RADIOBUTTON

Definition

 RadioButton class is used to create a radio button. It is used to choose one


option from multiple options.

 It is widely used in exam systems or quiz.

 It should be added in ButtonGroup to select one radio button only.

RadioButton class declaration

RadioButton Example Program:

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.

Adding Items to a ListView

It is possible to add items (options) to a ListView by obtaining its item


collection and add items to it. Here is an example that adds items to a
JavaFX 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.

ComboBox class declaration

15
Example:

 JComboBox is a part of Java Swing package.


 JComboBox inherits JComponent class .
 JComboBox shows a popup menu that shows a list and the user can
select a option from that specified list .
 JComboBox can be editable or read- only depending on the choice of
the programmer .

Constructor of the JComboBox are:

1. JComboBox() : creates a new empty JComboBox .


2. JComboBox(ComboBoxModel M) : creates a new JComboBox with items
from specified ComboBoxModel
3. JComboBox(E [ ] i) : creates a new JComboBox with items from specified
array.
4. JComboBox(Vector items) : creates a new JComboBox with items from
the specified vector

Commonly used Methods are :

1. addItem(E item) : adds the item to the JComboBox


2. addItemListener( ItemListener l) : adds a ItemListener to JComboBox
3. getItemAt(int i) : returns the item at index i
4. getItemCount(): returns the number of items from the list
5. getSelectedItem() : returns the item which is selected
6. removeItemAt(int i) : removes the element at index i

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

Constructor of the ChoiceBox class are:


1. ChoiceBox(): Creates a new empty ChoiceBox.
2. ChoiceBox(ObservableList items): Creates a new ChoiceBox with the
given set of items.

Commonly used methods


:
method explanation

getItems() Gets the value of the property items.

getValue() Gets the value of the property value.

hide() Closes the list of choices.

setItems(ObservableList value) Sets the value of the property items.

setValue(T value) Sets the value of the property value.

show() Opens the list of choices.

Example Program:

 This program creates a ChoiceBox named c and add a list of string to it


using(ChoiceBox(FXCollections.observableArrayList(string_array))).
 We would add the choice and a label to the tilepane(getChildren().add()
function).
 Then we will create a stage (container) and add the tilepane to the scene
and add the scene to the stage. Then display the stage using show()
function.

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
{

public void start(Stage s)


{
s.setTitle("creating ChoiceBox");
Button b = new Button("show");
TilePane r = new TilePane();
Label l = new Label("This is a choice box");
String st[] = { "Arnab", "Andrew", "Ankit", "None" };
ChoiceBox c = new ChoiceBox(FXCollections.observableArrayList(st));
r.getChildren().add(l);
r.getChildren().add(c);
Scene sc = new Scene(r, 200, 200);
s.setScene(sc);
s.show();
}

public static void main(String args[])


{
launch(args);
}
}

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.

Constructor of the TextField class :

1. TextField(): creates a new TextField with empty text content


2. TextField(String s): creates a new TextField with a initial text .

Commonly used methods:


method Explanation

Sets the value of the property


setPrefColumnCount(int v) prefColumnCount.

setOnAction(EventHandler
value) Sets the value of the property onAction.

setAlignment(Pos v) Sets the value of the property alignment.

prefColumnCountProperty() The preferred number of text columns

The action handler associated with this text


onActionProperty() field, or null if no action handler is assigned.

Gets the value of the property


getPrefColumnCount() prefColumnCount.

getOnAction() Gets the value of the property onAction.

getAlignment() Gets the value of the property alignment.

Returns the character sequence backing the


getCharacters() text field’s content.

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

public static void main(String args[])


{
launch(args);
}
}
Output:

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.

Create ScrollPane in JavaFX


Step 1:

 Accessing JavaFX features user-defined class must extend Application


class. In JavaFX creating ScrollPane .

 ScrollPane can instantiate by using the new keyword.

Syntax

ScrollPane scrollPane=new ScrollPane();

Step 2:

Adding content or scroll bar policies or setPannable properties to the scrollPane.

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:

TilePane tPane=new TilePane ();

Step 4:

Creating a scene means screen to display output .

Syntax:

22
Scene screen = new Scene(tPane, length, width);

Step 5:

Adding a Scene reference screen to the Stage object reference.

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

javafx.scene.layout Package provides various classes that represents the


layouts.

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

GridPane Organizes the nodes in the form of rows and columns.

HBox Organizes the nodes in a single row.

Pane It is the base class for all the layout classes.

StackPane Organizes nodes in the form of a stack i.e. one onto another

VBox Organizes nodes in a vertical column.

Steps to create layout

In order to create the layouts, we need to follow the following steps.

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

Alignment The overall alignment of the setAlignment(Pos value)


flowpane's content.

26
columnHalignmen The horizontal alignment of nodes setColumnHalignment(HPos
t within the columns. Value)

hgap Horizontal gap between the setHgap(Double value)


columns.

orientation Orientation of the flowpane setOrientation(Orientation


value)

prefWrapLength The preferred height or width setPrefWrapLength(double


where content should wrap in the value)
horizontal or vertical flowpane.

rowValignment The vertical alignment of the setRowValignment(VPos


nodes within the rows. value)

Vgap The vertical gap among the rows setVgap(Double value)

Constructors

There are 8 constructors in the class that are given below.

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;

public class FlowPaneTest extends Application

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:

HBox layout pane arranges the nodes in a single row. It is represented


by javafx.scene.layout.HBox class.

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.

Property Description Setter Methods

alignment This represents the alignment of the nodes. setAlignment(Double)

fillHeight This is a boolean property. If you set this property setFillHeight(Double)


to true the height of the nodes will become equal
to the height of the HBox.

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.

1. new HBox() : create HBox layout with 0 spacing


2. new Hbox(Double spacing) : create HBox layout with a spacing value

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:

 Vbox Layout Pane arranges the nodes in a single vertical column.


 It is represented by javafx.scene.layout.VBox class which provides all
the methods to deal with the styling and the distance among the nodes.

31
Properties

Property Description Setter Methods

Alignment This property is for the alignment of the nodes. setAlignement(Double)

FillWidth This property is of the boolean type. The setFillWidth(boolean)


Widtht of resizeable nodes can be made equal
to the Width of the VBox by setting this
property to true.

Spacing This property is to set some spacing among the setSpacing(Double)


nodes of VBox.

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.

Type Property Setter Methods Description

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

There are the following constructors in the class.

1. BorderPane() : create the empty layout


2. BorderPane(Node Center) : create the layout with the center node
3. BorderPane(Node Center, Node top, Node right, Node bottom, Node left)
: create the layout with all the nodes

Example Program of BorderPane:

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.

Propert Description Setter Method


y

alignment It represents the default alignment of setAlignment(Node child,


children within the StackPane's width and Pos value)
height setAlignment(Pos value)

Constructors

The class contains two constructors that are given below.

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:

 GridPane Layout pane allows us to add the multiple nodes in multiple


rows and columns.
 It is seen as a flexible grid of rows and columns where nodes can be
placed in any cell of the grid. It is represented
by javafx.scence.layout.GridPane class.

Properties
Property Description Setter Methods

Alignment Represents the alignment of the grid setAlignment(Pos value)


within the GridPane.

gridLinesVisibl This property is intended for setGridLinesVisible(Boolean


e debugging. Lines can be displayed to value)
show the gidpane's rows and columns
by setting this property to true.

Hgap Horizontal gaps among the columns setHgap(Double value)

vgap Vertical gaps among the rows setVgap(Double value)

37
Constructors

The class contains only one constructor that is given below.

o Public GridPane(): creates a gridpane with 0 hgap/vgap.

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:

 JavaFX provides a Menu class to implement menus.


 Menu is the main component of a any application.
 In JavaFX, javafx.scene.control.Menu class provides all the methods to
deal with menus.
 This class needs to be instantiated to create a Menu.

Implementation of JavaFX menu.


ManuBar menubar = new MenuBar();
Menu MenuName = new Menu("Menu Name");
MenuItem MenuItem1 = new MenuItem("Menu Item 1 Name");
MenuName.getItems().add(MenuItem1);
menubar.getMenus().add(MenuName);

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

JAVA JMENUBAR, JMENU AND JMENUITEM

 The JMenuBar class is used to display menubar on the window or frame.


It may have several menus.

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.

JMenuBar class declaration

public class JMenuBar extends JComponent implements MenuElement, Acces


sible
JMenu class declaration
public class JMenu extends JMenuItem implements MenuElement, Accessible

JMenuItem class declaration


public class JMenuItem extends AbstractButton implements Accessible, Menu
Element

Java JMenuItem and JMenu Example Program:


import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample()
{
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);

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

You might also like