0% found this document useful (0 votes)
26 views35 pages

Java Ex 10-15

The document describes how to develop a student management application using JavaFX controls. It involves creating a main method, implementing a start method to set up the UI, setting up event handlers for buttons, and implementing methods for the login and registration logic.
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)
26 views35 pages

Java Ex 10-15

The document describes how to develop a student management application using JavaFX controls. It involves creating a main method, implementing a start method to set up the UI, setting up event handlers for buttons, and implementing methods for the login and registration logic.
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/ 35

CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

EX.NO:10 Copy the contents of one file to another using file stream.
DATE:

AIM:
To write a java program to copy the contents of one file to
another using file stream

ALGORITHM:
1. Start the algorithm.
2. Define input and output file paths.
3. Create FileInputStream and FileOutputStream for source and
destination files.
4. Read from source file and write to destination file byte by byte
using a buffer.
5. Close FileInputStream and FileOutputStream to release system
resources.
6. If the process completes successfully, print "File copied
successfully."
7. If any errors occur, catch and handle them by printing an error
message.
8. End the algorithm.

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

PROGRAM:

import java.io.*;
public class FileCopy {
public static void main(String[] args) {
// Input and output file paths
String sourceFilePath = "source.txt";
String destinationFilePath = "destination.txt";

try {
// Create FileInputStream and FileOutputStream for source
and destination files
FileInputStream fileInputStream = new
FileInputStream(sourceFilePath);
FileOutputStream fileOutputStream = new
FileOutputStream(destinationFilePath);

// Read from source file and write to destination file byte by byte
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

// Close streams
fileInputStream.close();
fileOutputStream.close();
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

SAMPLE INPUT AND OUTPUT:

RESULT:
Thus java program to copy the contents of one file to another using
file stream is executed successfully.

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

EX.NO:11 Multi-threaded application


DATE:

AIM:
To implement a java program with multi-threading application
that has three threads.

ALGORITHM:

1. Begin the algorithm.


2. Define a class `R` extending `Thread` for generating random
numbers.
3. Define a class `S` extending `Thread` for computing squares of
even numbers.
4. Define a class `C` extending `Thread` for printing cubes of odd
numbers.
5. Implement the `run` method in each class to handle their
respective tasks.
6. Create a class `M` to hold shared variables and start the threads.
7. End the algorithm.

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

PROGRAM:

import java.util.Random;
class R extends Thread {
public void run() {
Random r = new Random();
while (true) {
int n = r.nextInt(100);
if (n % 2 == 0)
synchronized (M.l) {
M.e = n;
M.l.notifyAll();
}
else
synchronized (M.l) {
M.o = n;
M.l.notifyAll();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

}
}
class S extends Thread {
public void run() {
while (true) {
synchronized (M.l) {
while (M.e == -1) {
try {
M.l.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Square of " + M.e + ": " + (M.e * M.e));
M.e = -1;
}
}
}
}
class C extends Thread {
public void run() {
while (true) {
synchronized (M.l) {
while (M.o == -1) {

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

try {
M.l.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Cube of " + M.o + ": " + (M.o * M.o *
M.o));
M.o = -1;
}
}
}
}

class M {
static final Object l = new Object();
static int e = -1, o = -1;
public static void main(String[] args) {
new R().start();
new S().start();
new C().start();
}
}

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

SAMPLE INPUT AND OUTPUT:

RESULT:
Thus java program with multi-threading application that has three
threads is implemented successfully.

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

EX.NO:12 Implementation of two threads


DATE:

AIM:
To develop a java application that executes two threads.

ALGORITHM:

1. Start the algorithm.


2. Define a class `AlphabetPrinter` extending `Thread`.
3. Implement the `run` method in `AlphabetPrinter` to print
alphabets from the specified start character to 'Z' or vice versa, while
synchronizing on a shared lock object.
4. Create instances of `AlphabetPrinter` for printing alphabets from
'A' to 'Z' every one second and from 'Z' to 'A' every two seconds.
5. Start both threads.
6. Wait for both threads to finish using `join`.
7. Print a message indicating that all threads have finished execution.
8. End the algorithm.

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

PROGRAM:

class AlphabetPrinter extends Thread {


private final char startChar;
private final int sleepTime;
public AlphabetPrinter(char startChar, int sleepTime) {
this.startChar = startChar;
this.sleepTime = sleepTime;
}
@Override
public void run() {
for (char c = startChar; c >= 'A' && c <= 'Z'; c = (char) (startChar <
'Z' ? c + 1 : c - 1)) {
synchronized (Main.lock) {
System.out.println(c);
Main.lock.notify();
}
try {
Thread.sleep(sleepTime);
synchronized (Main.lock) {
if (c != 'Z') Main.lock.wait();
}
} catch (InterruptedException e) {

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

e.printStackTrace();
}
}
}
}
public class Main {
static final Object lock = new Object();
public static void main(String[] args) {
AlphabetPrinter firstThread = new AlphabetPrinter('A', 1000);
AlphabetPrinter secondThread = new AlphabetPrinter('Z', 2000);
firstThread.start();
secondThread.start();
try {
firstThread.join();
secondThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads finished execution.");
}
}

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING THEORY AND PRACTICES

SAMPLE INPUT AND OUTPUT:

RESULT:
Thus java application with two threads has been executed
successfully.

REGISTER NUMBER:2127220501113 PAGE NO.:


CS22409 – JAVA PROGRAMMING: THEORY AND PRACTICES

EXP. NO: 13
DATE:

JAVAFX CONTROLS

AIM:

To write a Java program to develop Student management application using


JavaFX controls

ALGORITHM:

1. Create the main method


- The `main()` method is the entry point of the application.
- It calls the `launch()` method to start the JavaFX application.

2. Implement the `start()` method


- The `start()` method is the main entry point for the JavaFX application.
- It creates the UI components, such as buttons, text fields, and labels.
- It sets up the layout using a `VBox` and adds the UI components to it.
- It creates a `Scene` object with the layout and sets it on the `Stage`.
- It sets the title of the `Stage` and shows it.

3. Set up event handlers


- The `setOnAction()` method is used to attach event handlers to the login
and register buttons.
- The `handleLogin()` method is called when the login button is clicked.

Roll no: 2127220501113 Page no:


- The `handleRegistration()` method is called when the register button is
clicked.

4. Implement the `handleLogin()` method


- This method takes the username and password entered by the user.
- For simplicity, it assumes a successful login and prints a message to the
console.
- In a real application, this method would implement the actual login
logic, such as checking the credentials against a database.

5. Implement the `handleRegistration()` method


- This method takes the username and password text fields as parameters.
- For simplicity, it assumes a successful registration and prints a message
to the console.
- In a real application, this method would implement the actual
registration logic, such as adding the new user to a database.

6. Clear the text fields after registration


- After a successful registration, the method clears the username and
password text fields.

7. Step 7: Run the application


- The `launch()` method in the `main()` method starts the JavaFX
application.
- The `start()` method is called, and the application window is displayed.

Roll no: 2127220501113 Page no:


PROGRAM:

import javafx.application.Application;

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.Label;

import javafx.scene.control.PasswordField;

import javafx.scene.control.TextField;

import javafx.scene.layout.GridPane;

import javafx.scene.layout.HBox;

import javafx.scene.paint.Color;

import javafx.scene.text.Font;

import javafx.scene.text.FontWeight;

import javafx.scene.text.Text;

import javafx.stage.Stage;

public class exp13 extends Application {

private String username = "admin";

private String password = "admin";

private TextField passwordTextField;

private TextField userTextField;

Roll no: 2127220501113 Page no:


public static void main(String[] args) {

launch(args);

@Override

public void start(Stage primaryStage) {

primaryStage.setTitle("JavaFX Login Example");

GridPane grid = new GridPane();

grid.setAlignment(Pos.CENTER);

grid.setHgap(10);

grid.setVgap(10);

grid.setPadding(new Insets(25, 25, 25, 25));

Text scenetitle = new Text("Welcome");

scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));

grid.add(scenetitle, 0, 0, 2, 1);

Label userName = new Label("User Name:");

grid.add(userName, 0, 1);

userTextField = new TextField();

grid.add(userTextField, 1, 1);

Roll no: 2127220501113 Page no:


Label pw = new Label("Password:");

grid.add(pw, 0, 2);

PasswordField passwordBox = new PasswordField();

grid.add(passwordBox, 1, 2);

passwordTextField = passwordBox;

CheckBox showPasswordCheckBox = new CheckBox("Show password");

showPasswordCheckBox.setOnAction(event -> {

if (showPasswordCheckBox.isSelected()) {

passwordBox.setPromptText(passwordBox.getText());

passwordBox.setText("");

passwordBox.setManaged(false);

passwordBox.setVisible(false);

passwordTextField = new TextField(passwordBox.getPromptText());

passwordTextField.setPromptText("Password");

grid.add(passwordTextField, 1, 2);

} else {

grid.getChildren().remove(passwordTextField);

passwordBox.setText(passwordTextField.getText());

passwordBox.setManaged(true);

passwordBox.setVisible(true);

passwordTextField = passwordBox;

Roll no: 2127220501113 Page no:


}

});

grid.add(showPasswordCheckBox, 1, 3);

Button btn = new Button("Sign in");

HBox hbBtn = new HBox(10);

hbBtn.setAlignment(Pos.CENTER);

hbBtn.getChildren().add(btn);

grid.add(hbBtn, 1, 4);

final Text actiontarget = new Text();

grid.add(actiontarget, 1, 6);

btn.setOnAction(e -> {

actiontarget.setText("");

String enteredUsername = userTextField.getText();

String enteredPassword = passwordTextField.getText();

if (enteredUsername.equals(username) &&
enteredPassword.equals(password)) {

actiontarget.setText("Login Successful");

actiontarget.setFill(Color.GREEN);

} else {

Roll no: 2127220501113 Page no:


actiontarget.setText("Login Unsuccessful");

actiontarget.setFill(Color.RED);

// Do not clear the text fields after sign-in

});

Scene scene = new Scene(grid, 300, 275);

primaryStage.setScene(scene);

primaryStage.show();

SAMPLE I/O:

RESULT:

Thus the Java Program to develop Student management application using


JavaFX controls has been implemented and executed successfully.

Roll no: 2127220501113 Page no:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

EX.NO:14a
LAYOUT USING FLOWPANE

DATE:

AIM:
To Develop a Java program to use a FlowPane layout in JavaFX to organize and
display a set of Label nodes.
ALGORITHM:
1. Initialize JavaFX Application:
• Define a class FlowPaneWidthDemo that extends Application.
• Define the main method within FlowPaneWidthDemo class to start the
JavaFX application by calling launch(args).
2. Override start Method:
• Override the start method of the Application class.
• The start method takes a Stage parameter, which represents the primary
stage of the application.
3. Create nine Label objects, each initialized with a unique text from "Label 1" to
"Label 9".
4. Create FlowPane:
• Create a FlowPane with horizontal and vertical gaps of 10 pixels.
• Add all nine Label objects to the labelPane.
5. Set the preferred wrap length of the labelPane to 150 pixels, which will cause it
to wrap its content to the next row when the width exceeds this value.
6. Create another FlowPane named rootNode and add the labelPane to it.
7. Create a Scene named myScene with the rootNode as its root node and a
width of 230 pixels and a height of 140 pixels.
8. Set myScene as the scene of the myStage.
9. Show the myStage along with its scene by calling myStage.show().

REGISTERNO:212722050113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

PROGRAM:

import javafx.application.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;

public class FlowPaneWidthDemo extends Application {


public static void main(String[] args) {
launch(args);
}
public void start (Stage myStage) {
myStage.setTitle("Demonstrate FlowPane Length");

Label one = new Label("Label 1");


Label two = new Label("Label 2");
Label three = new Label("Label 3");
Label four = new Label ("Label 4");
Label five = new Label ("Label 5");
Label six = new Label ("Label 6");
Label seven = new Label ("Label 7");
Label eight = new Label ("Label 8");
Label nine = new Label ("Label 9");

FlowPane labelPane = new FlowPane(10, 10);


labelPane.getChildren().addAll(one, two, three, four, five,six, seven, eight, nine);

labelPane.setPrefWrapLength (150);

FlowPane rootNode= new FlowPane();


rootNode.getChildren().add (labelPane);

Scene myScene= new Scene (rootNode, 230, 140);

myStage . setScene(myScene);

myStage.show();
}
}

REGISTERNO:212722050113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

SAMPLE INPUT AND OUTPUT:

RESULT:
Thus the Java program to use a FlowPane layout in JavaFX to organize and display
a set of Label nodes is successfully written and executed.

REGISTERNO:212722050113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

EX.NO:14b
LAYOUT USING BORDERPANE

DATE:

AIM:
To Develop a Java program showcasing the usage of BorderPane layout in JavaFX
for organizing controls in specific regions of the pane.
ALGORITHM:
1. Import necessary JavaFX packages for GUI implementation.
2. Define a class named BorderPaneDemo that extends Application.
3. Implement the main method to launch the JavaFX application (launch(args)).
4. Override the start method inherited from Application.
5. Initialize the stage (myStage) and set its title to "Demonstrate Border Pane".
6. Create a BorderPane (rootNode) to serve as the root layout container.
7. Create a Scene (myScene) with specified dimensions (340x200) and set it on the
stage.
8. Add graphical controls (TextField, Slider, Button, Label) to different regions
(Center, Right, Left, Top, Bottom) of the BorderPane.
9. Configure alignments and margins for controls within the BorderPane.
10. Display the stage (myStage) to show the GUI with the configured BorderPane
layout.

REGISTERNO:2127220501113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

PROGRAM:

import javafx.application.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

public class BorderPaneWidthDemo extends Application {


public static void main(String[] args) {
launch(args);
}
public void start (Stage myStage) {
myStage.setTitle("Demonstrate BorderPane Length");

public void start (Stage mystage) {


myStage.setTitle("Demonstrate BorderPane");
BorderPane rootNode = new BorderPane();
Scene myScene = new Scene (rootNode, 340, 200);
myStage.setScene (myScene):

//Center
TextField tfCenter = new TextField("This text field is in the center");
Border Pane.setAlignment (tfCenter, Pos.CENTER);
rootNode.setCenter(tfCenter);

//Right
Slider SldrRight = new Slider (0.0, 100.0, 50.0);
sldrRight.setOrientation (Orientation. VERTICAL);
sldrRight.setPrefWidth (60);
sldrRight. setShowTickLabels (true);
sldrRight.setShowTickMarks (true);
BorderPane.setAlignment (sldrRight, Pos.CENTER);
rootNode.setRight (sldrRight),

REGISTERNO:2127220501113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

//Left
Button btnAlpha = new Button("Alpha");
Button btnBeta = new Button("Beta");
Button btnGamma = new Button("Gamma");
btnAlpha.setPrefWidth(60);
btaBeta.setPrefWidth (60):
btnGamma.setPrefWidth(60);

Label vbLabel = new Label ("Vbox on left");

VBox vbLeft = new VBox (10);


vbLeft.getChildren().addAll (vbLabel, btnAlpha, binBeta, btnGamma);
vbLeft.setAlignment (Pos.CENTER);
rootNode.setLeft (vbLeft);
BorderPane.setAlignment (vbLeft, Pos.CENTER):

BorderPane. setMargin (vbleft, new Insets (10, 10, 10, 10));

//Top
Label lblTop = new Label ("This label is displayed along the top.");
BorderPane.setAlignment (lblTop, Pos.CENTER);
rootNode.setTop (lblTop);

//Bottom
Label lblBottom = new Label ("This label is displayed along the bottom.");
Border Pane.setAlignment (lblBottom, Pos.CENTER);
rootNode.setBottom (lblBottom);

myStage.show();

}
}

REGISTERNO:2127220501084 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

SAMPLE INPUT AND OUTPUT:

RESULT:
The Java program demonstrating the usage of BorderPane layout in JavaFX has
been executed successfully.

REGISTERNO:2127220501113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

EX.NO:14c
LAYOUT USING GRIDPANE

DATE:

AIM:
To write a Java program demonstrating the usage of the GridPane layout in JavaFX.
ALGORITHM:
1. Import necessary JavaFX packages for GUI implementation.
2. Define a class named GridPaneDemo that extends Application.
3. Implement the main method to launch the JavaFX application (launch(args)).
4. Override the start method inherited from Application.
5. Initialize the stage (myStage) and set its title ("Demonstrate GridPane").
6. Create TextField and Label objects for user input and descriptions.
7. Create a GridPane (rootNode) to organize controls in a grid layout.
8. Set padding around the GridPane using setPadding() method.
9. Set vertical and horizontal gaps between grid cells using setVgap() and setHgap()
methods.
10. Add labels and text fields to specific positions within the GridPane using add()
method with row and column indices.
11. Create a Scene (myScene) with the GridPane as its root node and set preferred
dimensions.
12. Set the created scene on the stage using setScene() method.
13. Display the stage to show the GUI with the configured GridPane layout and
controls.

REGISTERNO:2127220501113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

PROGRAM:

import javafx.application.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

public class GridPaneWidthDemo extends Application {


public static void main(String[] args) {
launch(args);
}
public void start (Stage myStage) {
myStage.setTitle("Demonstrate BorderPane Length");

public void start (Stage mystage) {


myStage.setTitle("Demonstrate GridPane");

// Create text fields and labels.


TextField tfName = new TextField();
tfName.setMaxWidth (120);
TextField tfPhone = new TextField();
tfPhone.setMaxWidth(120);
TextField tfEMail = new TextField();
tfEMail.setMaxWidth (120);

Label lblName = new Label ("Enter your name:");


Label lblPhone = new Label ("Enter your phone number:");
Label lblEMail = new Label ("Enter e-mail address.");

// Create the GridPane.


GridPane rootNode = new GridPane();
rootNode.setPadding (new Insets (10, 10, 10, 10));

// Set vertical and horizontal gaps between controls.


rootNode.setVgap (10);
rootNode.setHgap (20);

REGISTERNO:2127220501113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

// Add first column.


rootNode.add(lblName, 0, 0);
rootNode.add(lblPhone, 0, 1);
rootNode.add(lblEMail, 0, 2);

// Add second column.


rootNode.add(tfName, 1, 0);
rootNode.add (tfPhone, 1, 1);
rootNode.add (tfEMail, 1, 2);

// Create a scene.
Scene myScene = new Scene (rootNode, 300, 120);

// Set the scene on the stage. myStage.setScene (myScene);

// Show the stage and its scene.


myStage.show();

REGISTERNO:2127220501113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

SAMPLE INPUT AND OUTPUT:

RESULT:
The Java program showcasing the usage of the GridPane layout in JavaFX has
been successfully executed.

REGISTERNO:2127220501113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

EX.NO:15
JAVAFX MENU

DATE:

AIM:
To write a java program to showcase menu creation in javafx.
ALGORITHM:
1. Import necessary JavaFX packages for GUI implementation and define a class
named MenuDemo that extends Application.
2. Implement the main method, calling launch(args) to start the JavaFX
application and override the start method inherited.
3. Create a new Stage (myStage) for the application and set its title to
"Demonstrate Menus".
4. Create a BorderPane (rootNode) as the root layout container.
5. Create a Scene (myScene) with dimensions of 300x300 and set it for the stage
(myStage) and a MenuBar(mb) to hold menu items.
6. Define various Menu objects for organizing menu items.
7. Create MenuItem objects (open, close, save, exit, red, green, blue, high, low,
reset, about) representing actions in menus.
8. Configure menu hierarchy using getItems().addAll() and getMenus().add()
methods.
9. Implement an EventHandler<ActionEvent> (MEHandler) to handle menu item
selections and identify selected menu item using getText().
10.Perform specific actions based on the selected menu item.
11.Attach MEHandler to each menu item's setOnAction() method to respond to
user interactions.
12.Set the menu bar (mb) at the top and a Label (response) at the center of the
BorderPane (rootNode).
13.Display the stage (myStage) to show the GUI to the user.

REGISTERNO:2127220501113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

PROGRAM:

import javafx.application.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.event.*;
import javafx.geometry.*;

public class MenuDemo extends Application {


Label response;
public static void main(String[] args) {
launch(args);
}

// Override the start() method.


public void start(Stage myStage) {
myStage.setTitle(&quot;Demonstrate Menus&quot;);
BorderPane rootNode = new BorderPane();
Scene myScene = new Scene(rootNode, 300, 300);
myStage.setScene(myScene);
response = new Label(&quot;Menu Demo&quot;);

MenuBar mb = new MenuBar();


Menu fileMenu = new Menu(&quot;File&quot;);
MenuItem open = new MenuItem(&quot;Open&quot;);
MenuItem close = new MenuItem(&quot;Close&quot;);
MenuItem save = new MenuItem(&quot;Save&quot;);
MenuItem exit = new MenuItem(&quot;Exit&quot;);

fileMenu.getItems().addAll(open, close, save,new SeparatorMenuItem(), exit);


mb.getMenus().add(fileMenu);

Menu optionsMenu = new Menu(&quot;Options&quot;);


Menu colorsMenu = new Menu(&quot;Colors&quot;);
MenuItem red = new MenuItem(&quot;Red&quot;);
MenuItem green = new MenuItem(&quot;Green&quot;);
MenuItem blue = new MenuItem(&quot;Blue&quot;);
colorsMenu.getItems().addAll(red, green, blue);
optionsMenu.getItems().add(colorsMenu);

REGISTERNO:2127220501113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

// Create the Priority submenu.


Menu priorityMenu = new Menu(&quot;Priority&quot;);
MenuItem high = new MenuItem(&quot;High&quot;);
MenuItem low = new MenuItem(&quot;Low&quot;);
priorityMenu.getItems().addAll(high, low);
optionsMenu.getItems().add(priorityMenu);

// Add a separator.
optionsMenu.getItems().add(new SeparatorMenuItem());

//Create the Reset menu item.

MenuItem reset = new MenuItem(&quot;Reset&quot;);


optionsMenu.getItems().add(reset);

//Add Options menu to the menu bar.


mb.getMenus().add(optionsMenu);

Menu helpMenu = new Menu(&quot;Help&quot;);


MenuItem about = new MenuItem(&quot;About&quot;);
helpMenu.getItems().add(about);
mb.getMenus().add(helpMenu);

EventHandler&lt;ActionEvent&gt; MEHandler =
new EventHandler&lt;ActionEvent&gt;() { public void handle(ActionEvent ae) {
String name = ((MenuItem)ae.getTarget()).getText();
// If Exit is chosen, the program is terminated.
if(name.equals(&quot;Exit&quot;)) Platform.exit();
response.setText( name + &quot; selected&quot;);
}
};

// Set action event handlers for the menu items.


open.setOnAction(MEHandler);
close.setOnAction(MEHandler);
save.setOnAction(MEHandler);
exit.setOnAction(MEHandler);
red.setOnAction(MEHandler);
green.setOnAction(MEHandler);
blue.setOnAction(MEHandler);
high.setOnAction(MEHandler);
low.setOnAction(MEHandler);

REGISTERNO:2127220501113 PAGE NO:


CS22409- JAVA PROGRAMMING: THEORY AND PRACTICES

reset.setOnAction(MEHandler);
about.setOnAction(MEHandler);

//Add the menu bar to the top of the border pane and
//the response label to the center position.

rootNode.setTop(mb);
rootNode.setCenter(response);

myStage.show();
}
}

SAMPLE INPUT AND OUTPUT:

RESULT:
Thus the java program to showcase menu creation in javafx has been
implemented and the output has been verified successfully

REGISTERNO:2127220501113 PAGE NO:

You might also like