0% found this document useful (0 votes)
56 views34 pages

Practical 7 Gtu

Gtu Practical 7

Uploaded by

sinchain970
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)
56 views34 pages

Practical 7 Gtu

Gtu Practical 7

Uploaded by

sinchain970
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/ 34

Object Oriented Programming-I (3140705)

Index
(Progressive Assessment Sheet)

Sr. Objective(s) of Experiment Page Date of Date of Assessme Sign. of Remarks


No. No. perform submiss nt Teacher
ance ion Marks with date
1. To learn and understand the different basic
structures in java, such as syntax, logics, libraries
and proper indentation.
2. To learn Arrays and Strings in Java

3. To implement basic object-oriented concepts.

4. To implement basic object-oriented concepts.

5. To demonstrate the use of abstract classes and


interfaces.
6. To implement packages and exception handling in
JAVA application.
7. To demonstrate I/O from files.

8. To learn JAVA FX UI Controls.

9. To implement event handling and animation.

10. To learn recursion and generics.

Total
Object Oriented Programming-I (3140705)
Experiment No: 7

AIM: To demonstrate I/O from files.

Date: 27/03/2024

CO mapped: CO-4

Objectives:

To showcase proficiency in reading data from and writing data to files in various formats
using programming languages, demonstrating the ability to implement reliable and
efficient file I/O operations, which are essential for tasks such as data storage, retrieval,
and processing in software applications.

Background:
Java I/O (Input and Output) is used to process the input and produce the output. Java uses the
concept of a stream to make I/O operations fast. The java.io package contains all the classes
required for input and output operations.

Practical questions:
1. Write a program that removes all the occurrences of a specified string from a text file. For
example, invoking java Practical7_1 John filename removes the string John from the
specified file. Your program should read the string as an input.
Code: import java.io.*;

public class Practical7_1 {


public static void main(String[] args) {

if (args.length < 2) {
System.out.println("Usage: java RemoveStringFromFile string_to_remove
filename");
return;
}

String stringToRemove = args[0];


String filename = args[1];

try (

FileReader reader = new FileReader(filename);


BufferedReader bufferedReader = new BufferedReader(reader);
FileWriter writer = new FileWriter(filename + ".modified");
BufferedWriter bufferedWriter = new BufferedWriter(writer);
){
String line;
while ((line = bufferedReader.readLine()) != null) {
String modifiedLine = line.replace(stringToRemove, "");
bufferedWriter.write(modifiedLine);
bufferedWriter.newLine();
Object Oriented Programming-I (3140705)
}
} catch (IOException e) {
System.err.println("Error processing file: " + e.getMessage());
} catch (Exception e) {
throw new RuntimeException(e);
}

System.out.println("Successfully removed \"" + stringToRemove + "\" from " +


filename);

}
}
OUTPUT:

2. Write a program that will count the number of characters, words, and lines in a file. Words
are separated by whitespace characters. The file name should be passed as a command-line
argument.
Code: import java.io.*;

public class Practical7_2 {


public static void main(String[] args) throws IOException{
if (args.length < 1) {
System.out.println("Usage: java LineWordCharCounter filename.txt");
return;
}
Object Oriented Programming-I (3140705)
String filename = args[0];
int lines = 0;
int words = 0;
int chars = 0;

try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {


String line;
while ((line = reader.readLine()) != null) {
lines++;
words += line.trim().isEmpty() ? 0 : line.split("\\s+").length;
chars += line.length();
}
} catch (FileNotFoundException e) {
System.err.println("Error: File not found: " + filename);
}

System.out.println("Lines: " + lines);


System.out.println("Words: " + words);
System.out.println("Characters: " + chars);
}
}

OUTPUT:

Conclusion:

The experiment successfully demonstrated proficiency in reading data from and writing
data to files in a text format using Java. The provided code achieved the following objectives:

• Removed specific strings: Practical7_1 effectively removed all occurrences of a user-


specified string from a text file.
• Counted lines, words, and characters: Practical7_2 accurately counted the number of
lines, words, and characters within a text file.

These functionalities showcase essential file I/O operations crucial for data storage, retrieval, and
processing in software applications.
Object Oriented Programming-I (3140705)

Quiz:

1. What is file input/output (I/O), and why is it important in software development?

Answer: File I/O refers to the process of reading data from and writing data to files on a
storage device. It's fundamental in software development for several reasons:

• Data Persistence: Programs can store data beyond their execution, enabling
features like user preferences, application state, and historical records.
• Data Sharing: Data can be exchanged between programs or transferred across
systems by storing it in files.
• Data Processing: Large datasets can be efficiently processed by reading them
from files, manipulating the information, and potentially writing the results back to
a file.

2. What are the common modes for opening files, and how do they differ (e.g., read, write,
append)?

Answer: There are primary modes for opening files, each controlling how data can be
accessed:

• Read (r): Opens a file for reading existing content. Attempts to write to the file
will result in an error.
• Write (w): Creates a new file or overwrites an existing one. Any existing data will
be lost.
• Append (a): Opens a file for writing data at the end of the existing content. If the
file doesn't exist, it will be created.

3. Describe the concept of file streams and how they are used in file I/O operations.

Answer: File streams represent a flow of data between a program and a file. They act as
an abstraction layer, simplifying file I/O operations. There are two main types of streams:

• Input Streams: Used for reading data from a file. The experiment utilizes
FileReader and BufferedReader for this purpose.
• Output Streams: Used for writing data to a file. The experiment uses FileWriter
and BufferedWriter as examples.

4. Write short notes about I/O stream classes.

Answer: The provided Java code demonstrates the following I/O stream classes:

• FileReader: An InputStream class that reads characters from a file.


• BufferedReader: A buffering layer on top of FileReader, improving reading
performance.
• FileWriter: An OutputStream class that writes characters to a file.
• BufferedWriter: A buffering layer on top of FileWriter, improving writing
performance.
Object Oriented Programming-I (3140705)
These classes provide methods for reading/writing characters, lines, and even entire objects (with
additional libraries) to and from files.

Suggested Reference:

1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/

References used by the students:


1. https://www.geeksforgeeks.org/
2. https://www.w3schools.com/java/
3. https://www.javatpoint.com/

Rubric wise marks obtained:

Rubrics Criteria Need Good Excellent Total


Improvement

Marks Design of Program has Program has slight Program is


logic (4) significant logic errors that do logically well
logic errors. no significantly designed (3)
Correct (1) affect the results
output (4) (2)
Output has
Mock viva multiple Output has minor Program
test (2) errors. (1) errors. (2) displays correct
output with no
Delayed & Partially correct errors (3)
only few response (1)
correct All questions
answers (1) responded
Correctly (2)

Signature of Faculty:
Object Oriented Programming-I (3140705)

Experiment No: 8

AIM: To learn JAVA FX UI Controls.

Date: 03/04/2024

CO mapped: CO-5

Objectives:

a) To gain proficiency in JavaFX UI controls, including understanding their features and


capabilities, and developing the ability to create interactive and visually appealing
userinterfaces for Java applications. This knowledge will enable the design and
development of user-friendly, responsive, and feature-rich graphical user interfaces (GUIs)
in Java applications.
b) Learning JavaFX UI controls is essential for creating modern and engaging graphical user
interfaces for Java applications. This objective emphasizes not only understanding the
various UI controls but also the practical skills to design and implement user interfaces
effectively.

Background:
Every user interface considers the following three main aspects –

UI elements − These are the core visual elements that 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 practical.
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 that occur when the user interacts with UI elements.
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.

Common elements in a JavaFX application


All JavaFX applications contain the following elements:
1. A main window, called a stage in JavaFX.
2. At least one Scene in the stage.
3. A system of panes and boxes to organize GUI elements in the scene.
4. One or more GUI elements, such as buttons and labels.
The usual procedure for setting up a scene is to build it from the bottom up. First, we make the
GUI elements, then we make boxes and panes to organize the elements, and finally, we put
everything in the scene.
All JavaFX elements such as boxes and panes that are meant to contain other elements have a
child list that we can access via the getChildren() method. We put elements inside other elements
by adding things to child lists. In the code above you can see the button and the label objects
being added as children of a VBox, and the VBox, in turn, is set as the child of a StackPane.
Object Oriented Programming-I (3140705)
In addition to setting the structure for the window, we also call methods designed to set the
properties of various elements. For example, the code in this example uses the button's setText()
method to set the text the button will display.
Follow the procedure outlined in the section above to make a new JavaFX application. Replace
the start() method in the App class with the following code:
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");

StackPane root = new StackPane();


VBox box = new VBox();
box.getChildren().add(btn);
Label label = new Label();
box.getChildren().add(label);
root.getChildren().add(box);

btn.setOnAction(new ClickHandler(label));

Scene scene = new Scene(root, 300, 250);

primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}

Practical questions:
1. Write a program that displays five texts vertically, as shown in Figure. Set a random color
and opacity for each text and set the font of each text to Times Roman, bold, italic, and 22
pixels.
Object Oriented Programming-I (3140705)

Code:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.text.*;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Practical8_1 extends Application {


@Override
public void start(Stage primaryStage) {

HBox hBox = new HBox(10);


hBox.setPadding(new Insets(10, 10, 10, 10));
hBox.setAlignment(Pos.CENTER);

for (int i = 0; i < 5; i++) {


Text text = new Text("Java");
text.setFont(Font.font("Times Roman", FontWeight.BOLD,
FontPosture.ITALIC, 22));
text.setRotate(90);

text.setFill(new Color(Math.random(), Math.random(),


Math.random(), Math.random()));
hBox.getChildren().add(text);
}

Scene scene = new Scene(hBox, 300, 100);


primaryStage.setTitle("Exercise_14_04");
primaryStage.setScene(scene);
primaryStage.show();
}
}
OUTPUT:

2. Write a program that uses a bar chart to display the percentages of the overall grade
represented by projects, quizzes, midterm exams, and the final exam, as shown in Figure
Object Oriented Programming-I (3140705)
b. Suppose that projects take 20 percent and are displayed in red, quizzes take 10 percent
and are displayed in blue, midterm exams take 30 percent and are displayed in green, and
the final exam takes 40 percent and is displayed in orange. Use the Rectangle class to
display the bars. Interested readers may explore the JavaFXBarChart class for further
study.

Code:
\
package org.example.practical8_1;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.shape.Rectangle;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.layout.StackPane;
import javafx.geometry.Pos;
import javafx.scene.text.Text;
import javafx.scene.paint.Color;
import javafx.geometry.Insets;

public class Practical8_2 extends Application {


@Override
public void start(Stage primaryStage) {

HBox hBox = new HBox(15);


hBox.setAlignment(Pos.BOTTOM_CENTER);

String[] type = {"Project", "Quiz", "Midterm", "Final"};


double[] grade = {57, 6, 21, 46};

double max = getMax(grade);

double height = 200;


double width = 150;

StackPane pane = new StackPane();


pane.setPadding(new Insets(20, 15, 5, 15));

Rectangle r1 = new Rectangle(0, 0, width, height * grade[0] / max);


r1.setFill(Color.RED);
Rectangle r2 = new Rectangle(0, 0, width, height * grade[1] / max);
r2.setFill(Color.BLUE);
Rectangle r3 = new Rectangle(0, 0, width, height * grade[2] / max);
r3.setFill(Color.GREEN);
Object Oriented Programming-I (3140705)
Rectangle r4 = new Rectangle(0, 0, width, height * grade[3] / max);
r4.setFill(Color.ORANGE);

Text t1 = new Text(0, 0, type[0] + " -- " + grade[0] + "%");


Text t2 = new Text(0, 0, type[1] + " -- " + grade[1] + "%");
Text t3 = new Text(0, 0, type[2] + " -- " + grade[2] + "%");
Text t4 = new Text(0, 0, type[3] + " -- " + grade[3] + "%");

hBox.getChildren().addAll(getVBox(t1, r1), getVBox(t2, r2),


getVBox(t3, r3), getVBox(t4, r4));
pane.getChildren().add(hBox);

Scene scene = new Scene(pane);


primaryStage.setTitle("Practical8_2");
primaryStage.setScene(scene);
primaryStage.show();
}

public double getMax(double[] l) {


double max = l[0];
for (int i = 0; i < l.length; i++) {
if (l[i] > max)
max = l[i];
}
return max;
}

public VBox getVBox(Text t, Rectangle r) {


VBox vBox = new VBox(5);
vBox.setAlignment(Pos.BOTTOM_LEFT);
vBox.getChildren().addAll(t, r);
return vBox;
}
}
OUTPUT:

3. Write a program that displays a rectanguloid, as shown in Figure a. The cube should grow
and shrink as the window grows or shrinks.
Object Oriented Programming-I (3140705)

Code:
package org.example.practical8_1;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import java.util.ArrayList;

public class Practical8_3 extends Application {

@Override
public void start(Stage primaryStage) {

Pane pane = new Pane();

ArrayList<Shape> shapes = new ArrayList<>();

Rectangle rec1 = new Rectangle(0,0, Color.TRANSPARENT);


rec1.setStroke(Color.BLACK);
rec1.xProperty().bind(pane.widthProperty().divide(4).subtract(25));
rec1.yProperty().bind(pane.heightProperty().divide(4).add(25));
rec1.widthProperty().bind(pane.widthProperty().divide(2));
rec1.heightProperty().bind(pane.widthProperty().divide(2));
Object Oriented Programming-I (3140705)
shapes.add(rec1);

Rectangle rec2 = new Rectangle(0,0, Color.TRANSPARENT);


rec2.setStroke(Color.BLACK);
rec2.xProperty().bind(pane.widthProperty().divide(4).add(25));
rec2.yProperty().bind(pane.heightProperty().divide(4).subtract(25));
rec2.widthProperty().bind(pane.widthProperty().divide(2));
rec2.heightProperty().bind(pane.widthProperty().divide(2));
shapes.add(rec2);

Line line1 = new Line();


line1.startXProperty().bind(rec1.xProperty());
line1.startYProperty().bind(rec1.yProperty());
line1.endXProperty().bind(rec2.xProperty());
line1.endYProperty().bind(rec2.yProperty());
shapes.add(line1);

Line line2 = new Line();


line2.startXProperty().bind(rec1.xProperty());
line2.startYProperty().bind(rec1.yProperty().add(rec1.heightProperty()));
line2.endXProperty().bind(rec2.xProperty());
line2.endYProperty().bind(rec2.yProperty().add(rec1.heightProperty()));
shapes.add(line2);

Line line3 = new Line();


line3.startXProperty().bind(rec1.xProperty().add(rec1.widthProperty()));
line3.startYProperty().bind(rec1.yProperty().add(rec1.heightProperty()));
line3.endXProperty().bind(rec2.xProperty().add(rec1.widthProperty()));
line3.endYProperty().bind(rec2.yProperty().add(rec1.heightProperty()));
shapes.add(line3);

Line line4 = new Line();


line4.startXProperty().bind(rec1.xProperty().add(rec1.widthProperty()));
line4.startYProperty().bind(rec1.yProperty());
line4.endXProperty().bind(rec2.xProperty().add(rec1.widthProperty()));
line4.endYProperty().bind(rec2.yProperty());
shapes.add(line4);

pane.getChildren().addAll(shapes);
Scene scene = new Scene(pane, 400, 400);
scene.xProperty().add(scene.yProperty());
primaryStage.setTitle("Welcome to Java");
primaryStage.setScene(scene);
primaryStage.show();

public static void main(String[] args) {


Application.launch(args);

}
Object Oriented Programming-I (3140705)
}

OUTPUT:

Conclusion:

This experiment successfully explored JavaFX UI controls, achieving the following


objectives:

• Understanding Features and Capabilities: Through practical exercises, we gained


proficiency in various UI controls, including buttons, labels, panes, and layouts. We
learned how to manipulate their properties such as text, color, size, and position.
• Interactive and Visually Appealing Interfaces: The exercises demonstrated creating
interactive elements (buttons with actions) and applying visual styles (fonts, colors) to
design user-friendly and visually appealing interfaces.
• Practical Skills Development: By implementing programs with diverse UI components,
we honed our practical skills in designing and implementing user interfaces effectively.

This hands-on approach provided a solid foundation for crafting user-friendly, responsive, and
feature-rich GUIs for Java applications. We explored essential concepts like UI elements, layouts,
and event handling, laying the groundwork for further exploration of advanced JavaFX controls
and functionalities.

Quiz:

1. Explain the evolution of Java GUI technologies since awt,swing and JavaFX.
Answer:
• AWT (Abstract Window Toolkit): The original Java GUI toolkit, introduced in 1995.
It provided basic UI components like buttons, labels, and text fields. However, AWT
relied heavily on the native OS look and feel, leading to inconsistencies across platforms.

• Swing (Java Foundation Classes): Released in 1998, Swing built upon AWT, offering
richer UI components written entirely in Java. This ensured a more consistent look and
feel across different operating systems. Swing remains a powerful and widely used toolkit.
Object Oriented Programming-I (3140705)
• JavaFX: Introduced in 2008 by Sun Microsystems (now Oracle), JavaFX aimed to be a
modern replacement for Swing. It utilizes hardware acceleration for smoother animations
and effects. JavaFX also embraces modern UI design principles and integrates well with
multimedia features.

2. What is the purpose of a TextField control, and how can it be used to collect user input?

Answer: A TextField control is a single-line input field that allows users to enter text data.
It's ideal for collecting user input such as names, email addresses, or short descriptions.

• Collecting User Input:


1. Create a TextField object.
2. Set properties like text (initial content displayed) and prompt text (a hint
displayed when the field is empty).
3. Use an setOnAction event handler to capture the user's input when they
press Enter or the text field loses focus. Inside the handler, you can access
the entered text using the getText method of the TextField object.

3. How to create an ImageView from an Image, or directly from a file or a URL?.

Answer: There are three ways to create an ImageView in JavaFX:

• From an Image Object:


1. Load the image using new Image("imagePath").
2. Create an ImageView object and pass the loaded Image object to its
constructor.
• From a File:
1. Create an ImageView object directly, passing the file path to its constructor:
new ImageView("imagePath").
• From a URL:
1. Create an ImageView object, passing the image URL to its constructor: new
ImageView("http://example.com/image.jpg") .

4. What are the primary layout controls in JavaFX, and how do they impact the arrangement
of UI components?

Answer: JavaFX offers several layout controls to arrange UI components within a scene:

• HBox: Arranges elements horizontally from left to right.


• VBox: Arranges elements vertically from top to bottom.
• GridPane: Organizes elements in a grid-like structure with rows and columns.
• FlowPane: Places elements in the available space from left to right, wrapping to
the next line when full.
• StackPane: Overlaps elements on top of each other, with the last added element on
top.

These layout controls impact the arrangement by defining the position and sizing behavior
of child elements within them. For instance, an HBox ensures all child elements share the
same height and are placed side-by-side.
Object Oriented Programming-I (3140705)

5. What is CSS, and how is it used for styling JavaFX UI controls?

Answer: Cascading Style Sheets (CSS) is used to define the visual appearance of JavaFX
UI controls. You can separate the styling information from the Java code, promoting better
code organization and maintainability.

• Applying CSS:
1. Create a CSS file with styles for various control classes (e.g., .button,
.text-field).
2. In your Java code, set the style property of the control object with the
desired CSS class name. This links the control to the corresponding styles
defined in the CSS file.

By using CSS, you can control properties like fonts, colors, backgrounds, borders,
padding, and margins, allowing for customization of the look and feel of your JavaFX
application.

Suggested Reference:

1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/

References used by the students:


1. https://www.geeksforgeeks.org/
2. https://www.w3schools.com/java/
3. https://www.javatpoint.com/
Object Oriented Programming-I (3140705)
Rubric wise marks obtained:

Rubrics Criteria Need Good Excellent Total


Improvement

Marks Design of Program has Program has slight Program is


logic (4) significant logic errors that do logically well
logic errors. no significantly designed (3)
Correct (1) affect the results
output (4) (2)
Output has
Mock viva multiple Output has minor Program
test (2) errors. (1) errors. (2) displays correct
output with no
Delayed & Partially correct errors (3)
only few response (1)
correct All questions
answers (1) responded
Correctly (2)

Signature of Faculty:
Object Oriented Programming-I (3140705)

Experiment No: 9

AIM: To implement event handling and animation.

Date: 24/04/2024

CO mapped: CO-5

Objectives:

To proficiently implement event handling and animation in software applications,


fostering user interaction and engagement. Mastery of event-driven programming and
animation techniques will empower the creation of dynamic, responsive, and visually
captivating software experiences that cater to user needs and preferences.

Background:

Responding to user events


For a GUI application to be interactive, various elements such as buttons have to be able to
respond to interactions from the user, such as clicks. In GUI applications user actions such as
mouse clicks and key presses are called events. To set up an element such as a button to respond
to user events, we arrange to connect special event handling code to the button.
Our first example demonstrates one way to do this in JavaFX. The first step is to connect an
object to the button as the button's event handler via the button's setOnAction() method. The
requirement here is that the object that we link to the button has to implement a particular
interface, the EventHandler<ActionEvent> interface. That interface has one method in it, a
handle() method that will get called when the user clicks on the button.
For the event handler code to do something useful, it will typically need to have access to one or
more elements in the scene that will be affected by the button click. In this example, clicking the
button will trigger a change in the text displayed in a label in the scene. To make this all work, the
class we set up needs to have a member variable that is a reference to the label object. The code in
handle() will use that reference to change the text shown in the label when the user clicks on the
button.
Also, insert the code for the following class at the bottom of the App.java file:
classClickHandler implements EventHandler<ActionEvent> {
publicClickHandler(Label label) {
this.label = label;
}

public void handle(ActionEventevt) {


label.setText("Hello, World!");
}
Object Oriented Programming-I (3140705)
private Label label;
}

A better way to handle events


Although the process for linking an event handler to a button is fairly straightforward, it is a little
clunky. This process can get even more tedious when we start building applications with many
buttons that need event handlers. As a fix for this, JavaFX allows us to use a simpler mechanism
to set up event handlers.
To see how this mechanism works, remove the ClickHandler class completely and replace the line
of code in start() that calls the button's setOnAction() method with this:
btn.setOnAction((e)->{label.setText("Hello, World!");});
The ClickHandler class that you just eliminated had a handle() method in it. That method took a
single parameter, which was an ActionEvent object, e. The code we just put in place of the
original code contains a lambda expression mapping that parameter e to a chunk of code that will
run when the event takes place. This code is the code that used to live in the body of the handle()
method. The new statement saves a lot of space over the original. The lambda expression replaces
the ClickHandler class and its handle() method with a simpler alternative.
Practical questions:
1. Write a program that can dynamically change the font of a text in a label displayed on a
stack pane. The text can be displayed in bold and italic at the same time. You can select
the font name or font size from combo boxes, as shown in Figure. The available font
names can be obtained using Font.getFamilies(). The combo box for the font size is
initialized with numbers from 1 to 100.

Code:
\
package org.example.practical9;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
Object Oriented Programming-I (3140705)
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.CheckBox;
import javafx.geometry.Pos;
import javafx.geometry.Insets;
import java.util.List;
import java.util.ArrayList;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

public class Practical9_1 extends Application {


protected Text text = new Text("Programming is fun");
protected ComboBox<String> cboFontName = new ComboBox<>();
protected ComboBox<String> cboFontSize = new ComboBox<>();
protected CheckBox chkBold = new CheckBox("Bold");
protected CheckBox chkItalic = new CheckBox("Italic");

@Override
public void start(Stage primaryStage) {

List<String> families = Font.getFamilies();


ObservableList<String> fonts =
FXCollections.observableArrayList(families);
cboFontName.getItems().addAll(fonts);

ArrayList<String> list = new ArrayList<>();


for (int i = 1; i <= 100; i++) {
list.add(String.valueOf(i));
}
ObservableList<String> sizes =
FXCollections.observableArrayList(list);
cboFontSize.getItems().addAll(sizes);

HBox paneForComboBoxes = new HBox(5);


paneForComboBoxes.setAlignment(Pos.CENTER);
paneForComboBoxes.getChildren().addAll(
new Label("Font Name"), cboFontName,
new Label("Font Size"), cboFontSize);

text.setFont(Font.font(50));
StackPane paneForText = new StackPane(text);
paneForText.setPadding(new Insets(20, 5, 20, 5));

HBox paneForCheckBoxes = new HBox(5);


paneForCheckBoxes.setAlignment(Pos.CENTER);
paneForCheckBoxes.getChildren().addAll(chkBold, chkItalic);

cboFontName.setValue("Times New Roman");


Object Oriented Programming-I (3140705)
cboFontSize.setValue("30");
text.setFont(Font.font(getName(),
getWegiht(), getPosture(), getSize()));

chkBold.setOnAction(e -> setDisplay());


chkItalic.setOnAction(e -> setDisplay());
cboFontName.setOnAction(e -> setDisplay());
cboFontSize.setOnAction(e -> setDisplay());

BorderPane pane = new BorderPane();


pane.setTop(paneForComboBoxes);
pane.setCenter(paneForText);
pane.setBottom(paneForCheckBoxes);

Scene scene = new Scene(pane, 1000, 500);


primaryStage.setTitle("Practical9_1"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}

private void setDisplay() {


text.setFont(Font.font(getName(), getWegiht(), getPosture(), getSize()));
}

private String getName() {


return cboFontName.getValue();
}

private FontWeight getWegiht() {


return chkBold.isSelected() ? FontWeight.BOLD : FontWeight.NORMAL;
}

private FontPosture getPosture() {


return chkItalic.isSelected() ? FontPosture.ITALIC : FontPosture.REGULAR;
}

private int getSize() {


return Integer.parseInt(cboFontSize.getValue());
}
}
Object Oriented Programming-I (3140705)

OUTPUT-1:

OUTPUT-2:

2. Write a program that displays a moving text, as shown in Figure. The text moves from left
to right circularly. When it disappears in the right, it reappears from the left. The text
freezes when the mouse is pressed and moves again when the button is released.

Code:

package org.example.practical9;
import javafx.application.Application;
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.scene.Scene;
Object Oriented Programming-I (3140705)
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Practical9_2 extends Application {


@Override
public void start(Stage primaryStage) {

Pane pane = new Pane();

Text text = new Text("Programing is fun");


pane.getChildren().add(text);

PathTransition pt = new PathTransition(Duration.millis(10000),


new Line(-50, 50, 250, 50), text);
pt.setCycleCount(Timeline.INDEFINITE);
pt.play();

pane.setOnMousePressed(e -> {
pt.pause();
});

pane.setOnMouseReleased(e -> {
pt.play();
});

Scene scene = new Scene(pane, 200, 100);


primaryStage.setTitle("Practical9_2");
primaryStage.setScene(scene);
primaryStage.show();
}
}

OUTPUT-1:
Object Oriented Programming-I (3140705)

OUTPUT-2:

3. Create animation in Figure to meet the following requirements:

■ Allow the user to specify the animation speed in a text field.

■ Get the number of iamges and image’s file-name prefix from the user. For example, if the
user enters n for the number of images and L for the image prefix, then the files are L1.gif,
L2.gif, and so on, to Ln.gif. Assume that the images are stored in the image directory, a
subdirectory of the program’s class directory. The animation displays the images one after the
other.

■ Allow the user to specify an audio file URL. The audio is played while the animation runs.

Code:

package org.example.practical9;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.control.Button;
Object Oriented Programming-I (3140705)
import javafx.scene.control.TextField;
import javafx.scene.control.Label;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.geometry.Pos;
import javafx.geometry.HPos;
import javafx.util.Duration;

public class Practical9_3 extends Application {


protected TextField tfSpeed = new TextField();
protected TextField tfPrefix = new TextField();
protected TextField tfNumberOfImages = new TextField();
protected TextField tfURL = new TextField();
protected StackPane paneForImage = new StackPane();
protected Timeline animation;
protected int n = 1;

@Override
public void start(Stage primaryStage) {
final int COLUMN_COUNT = 27;
tfSpeed.setPrefColumnCount(COLUMN_COUNT);
tfPrefix.setPrefColumnCount(COLUMN_COUNT);
tfNumberOfImages.setPrefColumnCount(COLUMN_COUNT);
tfURL.setPrefColumnCount(COLUMN_COUNT);

Button btStart = new Button("Start Animation");


GridPane paneForInfo = new GridPane();
paneForInfo.setAlignment(Pos.CENTER);
paneForInfo.add(new Label("Enter information for animation"), 0, 0);
paneForInfo.add(new Label("Animation speed in milliseconds"), 0, 1);
paneForInfo.add(tfSpeed, 1, 1);
paneForInfo.add(new Label("Image file prefix"), 0, 2);
paneForInfo.add(tfPrefix, 1, 2);
paneForInfo.add(new Label("Number of images"), 0, 3);
paneForInfo.add(tfNumberOfImages, 1, 3);
paneForInfo.add(new Label("Audio file URL"), 0, 4);
paneForInfo.add(tfURL, 1, 4);
BorderPane pane = new BorderPane();
pane.setBottom(paneForInfo);
pane.setCenter(paneForImage);
pane.setTop(btStart);
pane.setAlignment(btStart, Pos.TOP_RIGHT);

animation = new Timeline(


new KeyFrame(Duration.millis(1000), e -> nextImage()));
animation.setCycleCount(Timeline.INDEFINITE);

btStart.setOnAction(e -> {
if (tfURL.getText().length() > 0) {
Object Oriented Programming-I (3140705)
MediaPlayer mediaPlayer = new MediaPlayer(
new Media(tfURL.getText()));
mediaPlayer.play();
}
if (tfSpeed.getText().length() > 0)
animation.setRate(Integer.parseInt(tfSpeed.getText()));
animation.play();
});

Scene scene = new Scene(pane, 550, 680);


primaryStage.setTitle("Practical9_3");
primaryStage.setScene(scene);
primaryStage.show();
}

private void getImage() {


paneForImage.getChildren().clear();
paneForImage.getChildren().add(new ImageView(new Image(
"http://cs.armstrong.edu/liang/common/image/" +
tfPrefix.getText() + n + ".gif")));
}

private void nextImage() {


n = n < Integer.parseInt(
tfNumberOfImages.getText()) ? n += 1 : 1;
getImage();
}
}

OUTPUT:

Conclusion:

This experiment successfully implemented event handling and animation techniques to


create interactive software experiences. We explored two methods for handling button clicks in
JavaFX: a traditional class-based approach and a more concise lambda expression approach.

The provided practical questions demonstrated the creation of programs that:

1. Dynamically change font properties based on user selection.


2. Animate text movement with mouse interaction control.
3. Allow user control over animation speed, image sequence, and audio playback.
Object Oriented Programming-I (3140705)
These exercises showcase the power of event-driven programming and animation in building
engaging and responsive user interfaces.

Quiz:

1. How does event handling work in Java, and what is the event-driven programming model?

Answer: Event handling in Java is a mechanism for programs to respond to user


interactions and other occurrences. It follows an event-driven programming model. Here's
how it works:

• Events: These are signals that something has happened within the program or the
user's environment (e.g., button click, key press, window resize).
• Event Sources: Objects that generate events (e.g., buttons, text fields, windows).
• Event Listeners: Objects that wait for and handle specific events from event
sources.
• Event Handlers: Methods within listeners that define the actions to be taken when
an event occurs.

2. What is the role of the java.awt.event and javafx.event packages in Java event handling?
Answer:
• java.awt.event: This package provides interfaces and classes for handling events in the
Abstract Window Toolkit (AWT) components like buttons, text fields, and windows. It's
used for traditional desktop applications.
• javafx.event: This package provides interfaces and classes for handling events in
JavaFX applications. It offers a more modern and declarative approach to event handling
compared to AWT.

3. Explain: MouseEvent, KeyEvent, ActionEvent

Answer: These are specific event types within the Java event handling system:

• MouseEvent: Represents events generated by mouse interactions with a


component (e.g., clicks, drags, hovers).
• KeyEvent: Represents events generated by keyboard interactions (e.g., key
presses, releases, and typed characters).
• ActionEvent: Represents events generated by user actions that cause a change in
an object's state (e.g., clicking a button, selecting an item from a menu).

4. What are the primary libraries or frameworks for creating animations in Java, and which
one do you prefer?

Answer: There are several options for animation in Java, but here are two popular ones:

• JavaFX: (Preferred) Built-in with Java, JavaFX offers a rich set of animation
classes and APIs for creating smooth and efficient animations. It integrates well
with JavaFX applications.
• Swing: A part of the Java AWT library, Swing provides some animation
capabilities, but it can be less versatile and more complex compared to JavaFX.
Object Oriented Programming-I (3140705)
5. How to set the cycle count of an animation to infinite?

Answer: There are two ways to achieve an infinite cycle count depending on the
animation library you're using:

• JavaFX: Use setCycleCount(Animation.INDEFINITE) on your animation


object.
• Swing: Implement a custom ActionListener and restart the animation within the
actionPerformed method when the animation finishes.

Suggested Reference:

1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/

References used by the students:


1. https://www.geeksforgeeks.org/
2. https://www.w3schools.com/java/
3. https://www.javatpoint.com/

Rubric wise marks obtained:

Rubrics Criteria Need Good Excellent Total


Improvement

Marks Design of Program has Program has slight Program is


logic (4) significant logic errors that do logically well
logic errors. no significantly designed (3)
Correct (1) affect the results
output (4) (2)
Output has
Mock viva multiple Output has minor Program
test (2) errors. (1) errors. (2) displays correct
output with no
Delayed & Partially correct errors (3)
only few response (1)
correct All questions
answers (1) responded
Correctly (2)

Signature of Faculty:
Object Oriented Programming-I (3140705)

Experiment No: 10

AIM: To learn recursion and generics.

Date: 01/05/2024

CO mapped: CO-4

Objectives:

a) To develop a deep understanding of recursion and generics in programming. Mastery of


recursion will enable the development of elegant and efficient algorithms for solving
complex problems. Understanding generics will facilitate the creation of flexible, reusable,
and type-safe code in various programming languages.

b) Learning recursion and generics is crucial for building efficient algorithms and writing
more versatile and type-safe code in software development. Achieving this objective will
help you become a more proficient and well-rounded programmer.

Background:

Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called the recursive method.
Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the
code stable by detecting the bugs at compile time. Before generics, we can store any type of
object in the collection, i.e., non-generic. Now generics force the java programmer to store a
specific type of object.

Practical questions:

1. Write a recursive method that converts a decimal number into a binary number as a string.
The method header is: public static String dec2Bin(int value)

• Write a test program that prompts the user to enter a decimal number and displays its
binary equivalent.
Code: import java.util.Scanner;
public class Practical10_1{

public static String dec2Bin(int value) {


if (value == 0) {
return "0";
} else {
return dec2Bin(value / 2) + (value % 2);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = scanner.nextInt();

String binary = dec2Bin(decimal);


Object Oriented Programming-I (3140705)
System.out.println("Binary equivalent: " + binary);
}
}
OUTPUT:

2. Write the following method that returns a new ArrayList. The new list contains the non-
duplicate elements from the original list.

• public static <E>ArrayList<E>removeDuplicates(ArrayList<E> list)


Code:
import java.util.ArrayList;
import java.util.Scanner;

public class Practical10_2 {


public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) {
ArrayList<E> uniqueList = new ArrayList<>();

for (int i = 0; i < list.size(); i++) {


E element = list.get(i);

boolean isDuplicate = false;


for (int j = i + 1; j < list.size(); j++) {
if (element.equals(list.get(j))) {
isDuplicate = true;
break;
}
}

if (!isDuplicate) {
uniqueList.add(element);
}
}

return uniqueList;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

ArrayList<Integer> num = new ArrayList<>();


System.out.println("How many Numbers you want to enter: ");
int n = sc.nextInt();
System.out.println("Enter "+n+" numbers");

for (int i=0; i<n; i++){


int temp = sc.nextInt();
Object Oriented Programming-I (3140705)
num.add(temp);
}

System.out.println("The Original List :"+ num);


ArrayList<Integer> uniqueNum = removeDuplicates(num);
System.out.println("The List without Duplicates: "+ uniqueNum);

}
}
OUTPUT:

Conclusion:

This experiment successfully achieved its goals of providing a deep understanding of


recursion and generics in programming.

We explored recursion through implementing a method dec2Bin(int value) that


converts a decimal number to its binary equivalent. This function demonstrates how a method can
call itself with a smaller version of the original problem until a base case is reached.

Generics were used in the removeDuplicates(ArrayList<E> list) method. This


function showcases how generics allow the creation of reusable code that can work with different
data types (represented by E) without compromising type safety.

By working through these practical exercises, we gained valuable insights into the power
and versatility of recursion and generics. These concepts are fundamental for building efficient
algorithms, writing clean and reusable code, and becoming a more proficient programmer.

Quiz:

1. What is recursion in Java, and how does it differ from iteration in solving problems?

Recursion is a programming technique where a method calls itself directly or indirectly. It


breaks down a problem into smaller subproblems of the same type until a base case is
reached, which can be solved directly.

Iteration, on the other hand, uses loops (like for or while) to solve problems by repeatedly
executing a block of code until a certain condition is met.
Object Oriented Programming-I (3140705)
The choice between recursion and iteration depends on the problem. Recursion can be
more elegant for problems that can be naturally divided into subproblems of the same
type. Iteration is often more efficient for simple repetitive tasks.

Feature Recursion Iteration


Problem-solving Breaks down problems into smaller Uses loops to repeatedly execute
approach subproblems of the same type a block of code
Suitability Problems with a natural recursive structure Simple repetitive tasks

2. What are the advantages and disadvantages of using recursion in Java?

Advantages

• Reads like natural language for problems that have a recursive structure.
• Can lead to more concise and elegant code.

Disadvantages

• Can be less efficient than iteration for simple problems due to function call
overhead.
• Can be difficult to debug due to the nested nature of calls.
• Can lead to stack overflow errors if not implemented carefully.

Feature Advantage Disadvantage


Reads like natural language for Can be complex for non-recursive
Readability recursive problems problems
May require more verbose code for
Conciseness Can lead to more concise code iterative solutions
Efficiency Less efficient for simple problems More efficient for simple problems
Can be difficult to debug due to nested
Debugging calls Easier to debug due to sequential nature
Stack Can lead to stack overflow errors if not
overflow careful No risk of stack overflow errors

3. What are generics in Java, and why are they used for creating parameterized types?

Generics allow you to write code that can work with different data types without
compromising type safety. They are implemented using parameterized types, which are
placeholders for specific data types that are specified when the generic code is used.

For example, a generic ArrayList can store any type of object, but once you create a
specific ArrayList of integers, it can only hold integers.

4. How to define Generic class? What are restrictions of generic programming?

A generic class is a class that can be parameterized with one or more types. These
types are specified using angle brackets ( <>) and act as placeholders for the actual data
types that will be used when the class is instantiated.
Object Oriented Programming-I (3140705)
Restrictions of generic programming:

• Generics cannot be used for primitive data types like int or float.
• You cannot create arrays of generic types.

5. Can you provide an example of a generic class in Java, such as a generic ArrayList?
import java.util.ArrayList;

public class GenericExample<T> {


private ArrayList<T> myList;

public GenericExample() {
myList = new ArrayList<>();
}

public void addItem(T item) {


myList.add(item);
}

public ArrayList<T> getList() {


return myList;
}

public static void main(String[] args) {


GenericExample<String> stringList = new GenericExample<>();
stringList.addItem("Hello");
stringList.addItem("World");
System.out.println("String List: " + stringList.getList());

GenericExample<Integer> integerList = new GenericExample<>();


integerList.addItem(1);
integerList.addItem(2);
System.out.println("Integer List: " + integerList.getList());
}
}

In this example, GenericExample is a generic class that can hold elements of any
type. The type parameter <T> allows us to specify the type of elements that this class will
work with. Inside the class, we use an ArrayList<T> to store elements of type T. The
addItem method adds an element to the list, and the getList method returns the list.

In the main method, we demonstrate how GenericExample can be instantiated with


different types (String and Integer). This flexibility is made possible by generics, allowing
us to create reusable and type-safe code.
Object Oriented Programming-I (3140705)
Suggested Reference:

1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/

References used by the students: (Sufficient space to be provided)

Rubric wise marks obtained:

Rubrics Criteria Need Good Excellent Total


Improvement

Marks Design of Program has Program has slight Program is


logic (4) significant logic errors that do logically well
logic errors. no significantly designed (3)
Correct (1) affect the results
output (4) (2)
Output has
Mock viva multiple Output has minor Program
test (2) errors. (1) errors. (2) displays correct
output with no
Delayed & Partially correct errors (3)
only few response (1)
correct All questions
answers (1) responded
Correctly (2)

Signature of Faculty:

You might also like