0% found this document useful (0 votes)
5 views19 pages

Abdullah 2

Uploaded by

Abdullah Afzal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views19 pages

Abdullah 2

Uploaded by

Abdullah Afzal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Task 1: You are tasked with creating a simple JavaFX application that displays a personalized

greeting message when a user enters their name and clicks a button.

A user opens the application and sees:

1. A TextField where they can type their name.


2. A Button labeled "Say Hello".
3. A Label that displays a greeting message.

When the user enters their name (e.g., "Alice") in the text field and clicks the "Say Hello" button,
the label updates to display "Hello, Alice!".

Requirements

1. Use JavaFX's TextField, Button, and Label components.


2. Implement an event handler for the button click to update the label with the greeting message.
3. Initialize the application with an empty text field and a label that displays a default message like
"Welcome!".

Code

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

import javafx.stage.Stage;

public class GreetingApp extends Application {

@Override

public void start(Stage primaryStage) {

// Create the TextField for user input

TextField nameField = new TextField();

nameField.setPromptText("Enter your name");


// Create the Button

Button sayHelloButton = new Button("Say Hello");

// Create the Label for displaying the greeting message

Label greetingLabel = new Label("Welcome!");

// Set the Button action

sayHelloButton.setOnAction(e -> {

String name = nameField.getText();

if (!name.isEmpty()) {

greetingLabel.setText("Hello, " + name + "!");

} else {

greetingLabel.setText("Please enter your name.");

});

// Arrange the UI components in a vertical box layout

VBox layout = new VBox(10, nameField, sayHelloButton, greetingLabel);

// Create the Scene with the layout

Scene scene = new Scene(layout, 300, 200);

// Set up the Stage (window)

primaryStage.setScene(scene);
primaryStage.setTitle("Greeting Application");

primaryStage.show();

public static void main(String[] args) {

launch(args);

Task 2: You are tasked with creating a JavaFX application that changes the background color of
the window when the user clicks a button.

The application starts with:

1. A window with a default white background.


2. A Button labeled "Change Color".

When the user clicks the "Change Color" button:

 The background color of the window changes to a random color.

Requirements

1. Use JavaFX's Button and Pane components.


2. Generate a random color using JavaFX's Color class.
3. Change the background color of the window's Pane each time the button is clicked.

Code
import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.Pane;

import javafx.scene.paint.Color;

import javafx.stage.Stage;
import java.util.Random;

public class ColorChangerApp extends Application {

@Override

public void start(Stage primaryStage) {

// Create a Pane for the background

Pane pane = new Pane();

pane.setStyle("-fx-background-color: white;"); // Set initial background color

// Create a Button to change color

Button changeColorButton = new Button("Change Color");

// Set the button's layout position

changeColorButton.setLayoutX(100);

changeColorButton.setLayoutY(100);

// Add the button to the pane

pane.getChildren().add(changeColorButton);

// Set the Button action to change the background color

changeColorButton.setOnAction(e -> {

Color randomColor = generateRandomColor();

pane.setStyle("-fx-background-color: " + toHexString(randomColor) + ";");

});
// Create the Scene with the pane

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

// Set up the Stage (window)

primaryStage.setScene(scene);

primaryStage.setTitle("Color Changer Application");

primaryStage.show();

// Method to generate a random color

private Color generateRandomColor() {

Random random = new Random();

return new Color(random.nextDouble(), random.nextDouble(), random.nextDouble(), 1.0);

// Method to convert Color to hex string

private String toHexString(Color color) {

return String.format("#%02X%02X%02X",

(int)(color.getRed() * 255),

(int)(color.getGreen() * 255),

(int)(color.getBlue() * 255));

public static void main(String[] args) {


launch(args);

You are tasked with creating a JavaFX application that increments a counter every time a button
is clicked.

The application starts with:

1. A Label displaying the number 0 (the counter's initial value).


2. A Button labeled "Increment".

Each time the user clicks the "Increment" button:

 The number displayed in the label increases by 1.

Requirements

1. Use JavaFX Label and Button components.


2. Update the label's text dynamically based on button clicks.
3. Keep the layout simple, with the label above the button.

Code:
import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.control.Label;

import javafx.scene.layout.VBox;

import javafx.stage.Stage;

public class CounterApp extends Application {

private int counter = 0; // Counter's initial value

@Override

public void start(Stage primaryStage) {


// Create the Label to display the counter's value

Label counterLabel = new Label("0");

// Create the Button to increment the counter

Button incrementButton = new Button("Increment");

// Set the Button action to increment the counter and update the Label

incrementButton.setOnAction(e -> {

counter++;

counterLabel.setText(String.valueOf(counter));

});

// Arrange the Label and Button in a vertical box layout

VBox layout = new VBox(10, counterLabel, incrementButton);

// Create the Scene with the layout

Scene scene = new Scene(layout, 200, 150);

// Set up the Stage (window)

primaryStage.setScene(scene);

primaryStage.setTitle("Counter Application");

primaryStage.show();

public static void main(String[] args) {


launch(args);

}
: Create a simple JavaFX application to convert temperatures between Celsius and Fahrenheit.
Task Description:

1. Layout:
 Add a Label for the title (e.g., "Temperature Converter").
 Add two TextField components for entering the temperature in Celsius and
Fahrenheit.
 Include two Buttons labeled "Convert to Fahrenheit" and "Convert to Celsius".
 Arrange the components using a VBox.
2. Functionality:
 Clicking "Convert to Fahrenheit" should calculate the Fahrenheit equivalent and
display it in the appropriate TextField.
 Clicking "Convert to Celsius" should calculate the Celsius equivalent and display
it.
3. Validation:
 Display an error message in a Label if the user enters invalid input.
4. Enhancement:
 Add tooltips to guide users on how to use the application.

Code:

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

import javafx.stage.Stage;

import javafx.scene.control.Tooltip;

public class TemperatureConverterApp extends Application {

@Override
public void start(Stage primaryStage) {

// Create the title label

Label titleLabel = new Label("Temperature Converter");

// Create the TextFields for Celsius and Fahrenheit inputs

TextField celsiusField = new TextField();

celsiusField.setPromptText("Enter Celsius");

Tooltip celsiusTooltip = new Tooltip("Enter the temperature in Celsius");

Tooltip.install(celsiusField, celsiusTooltip);

TextField fahrenheitField = new TextField();

fahrenheitField.setPromptText("Enter Fahrenheit");

Tooltip fahrenheitTooltip = new Tooltip("Enter the temperature in Fahrenheit");

Tooltip.install(fahrenheitField, fahrenheitTooltip);

// Create the buttons for conversion

Button toFahrenheitButton = new Button("Convert to Fahrenheit");

Button toCelsiusButton = new Button("Convert to Celsius");

// Create the label for displaying error messages

Label errorLabel = new Label();

// Set the button actions for conversion

toFahrenheitButton.setOnAction(e -> {

try {
double celsius = Double.parseDouble(celsiusField.getText());

double fahrenheit = celsius * 9/5 + 32;

fahrenheitField.setText(String.format("%.2f", fahrenheit));

errorLabel.setText(""); // Clear error message

} catch (NumberFormatException ex) {

errorLabel.setText("Invalid input for Celsius.");

});

toCelsiusButton.setOnAction(e -> {

try {

double fahrenheit = Double.parseDouble(fahrenheitField.getText());

double celsius = (fahrenheit - 32) * 5/9;

celsiusField.setText(String.format("%.2f", celsius));

errorLabel.setText(""); // Clear error message

} catch (NumberFormatException ex) {

errorLabel.setText("Invalid input for Fahrenheit.");

});

// Arrange the components in a VBox layout

VBox layout = new VBox(10, titleLabel, celsiusField, toFahrenheitButton, fahrenheitField,


toCelsiusButton, errorLabel);

// Create the scene with the layout

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


// Set up the stage (window)

primaryStage.setScene(scene);

primaryStage.setTitle("Temperature Converter");

primaryStage.show();

public static void main(String[] args) {

launch(args);

}
Home Task 2: To-Do List Manager
Build a basic To-Do List application.
Task Description:
1. Layout:
 Add a TextField for entering a task.
 Include an "Add Task" button to add the task to a list.
 Use a ListView to display the tasks.
 Add a "Remove Selected Task" button to delete a selected task.
 Arrange components using a VBox.
2. Functionality:
 Clicking "Add Task" should add the entered task to the ListView.
 Clicking "Remove Selected Task" should delete the selected task from the ListView.
3. Enhancement:
 Add a confirmation dialog (Alert) before deleting a task.

Code

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Alert;

import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;

import javafx.scene.control.Label;

import javafx.scene.control.ListView;

import javafx.scene.control.TextField;

import javafx.scene.control.Tooltip;

import javafx.scene.layout.VBox;

import javafx.stage.Stage;

public class ToDoListApp extends Application {

@Override

public void start(Stage primaryStage) {

// Create the TextField for entering tasks

TextField taskField = new TextField();

taskField.setPromptText("Enter a task");

Tooltip taskTooltip = new Tooltip("Type your task here");

Tooltip.install(taskField, taskTooltip);

// Create the "Add Task" button

Button addTaskButton = new Button("Add Task");

// Create the ListView to display tasks

ListView<String> taskListView = new ListView<>();

// Create the "Remove Selected Task" button

Button removeTaskButton = new Button("Remove Selected Task");


// Create the label for displaying error messages

Label errorLabel = new Label();

// Set the button action for adding a task

addTaskButton.setOnAction(e -> {

String task = taskField.getText();

if (!task.isEmpty()) {

taskListView.getItems().add(task);

taskField.clear();

errorLabel.setText(""); // Clear error message

} else {

errorLabel.setText("Please enter a task.");

});

// Set the button action for removing a selected task

removeTaskButton.setOnAction(e -> {

String selectedTask = taskListView.getSelectionModel().getSelectedItem();

if (selectedTask != null) {

// Show a confirmation dialog before deleting the task

Alert confirmationAlert = new Alert(AlertType.CONFIRMATION, "Are you sure you want to


delete the selected task?");

confirmationAlert.showAndWait().ifPresent(response -> {

if (response == AlertType.CONFIRMATION.getButtonData()) {

taskListView.getItems().remove(selectedTask);
}

});

} else {

errorLabel.setText("Please select a task to remove.");

});

// Arrange the components in a VBox layout

VBox layout = new VBox(10, taskField, addTaskButton, taskListView, removeTaskButton,


errorLabel);

// Create the scene with the layout

Scene scene = new Scene(layout, 300, 400);

// Set up the stage (window)

primaryStage.setScene(scene);

primaryStage.setTitle("To-Do List Manager");

primaryStage.show();

public static void main(String[] args) {

launch(args);

}
}
: Simple Calculator
Scenario: Create a basic calculator application to perform addition, subtraction, multiplication,
and division.
Task Description:
1. Layout:
 Add two TextField components for number input.
 Include four Buttons for "+", "-", "*", and "/".
 Add a Label to display the result.
 Use an HBox for the buttons and a VBox for the overall layout.
2. Functionality:
 Clicking a button should perform the corresponding operation and display the result in
the Label.
 Handle division by zero with an error message in the Label.
3. Validation:
 Ensure both inputs are valid numbers before performing any operation.

Code
import javafx.application.Application;

import javafx.geometry.Pos;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.control.Label;

import javafx.scene.control.TextField;

import javafx.scene.layout.HBox;

import javafx.scene.layout.VBox;

import javafx.stage.Stage;

public class SimpleCalculatorApp extends Application {

@Override

public void start(Stage primaryStage) {

// Create TextFields for number input


TextField numberField1 = new TextField();

numberField1.setPromptText("Enter first number");

TextField numberField2 = new TextField();

numberField2.setPromptText("Enter second number");

// Create Buttons for operations

Button addButton = new Button("+");

Button subtractButton = new Button("-");

Button multiplyButton = new Button("*");

Button divideButton = new Button("/");

// Create Label to display the result

Label resultLabel = new Label("Result will be displayed here");

// HBox for operation buttons

HBox buttonBox = new HBox(10, addButton, subtractButton, multiplyButton, divideButton);

buttonBox.setAlignment(Pos.CENTER);

// VBox for the overall layout

VBox layout = new VBox(10, numberField1, numberField2, buttonBox, resultLabel);

layout.setAlignment(Pos.CENTER);

// Set button actions for performing operations

addButton.setOnAction(e -> {

try {
double num1 = Double.parseDouble(numberField1.getText());

double num2 = Double.parseDouble(numberField2.getText());

double result = num1 + num2;

resultLabel.setText("Result: " + result);

} catch (NumberFormatException ex) {

resultLabel.setText("Please enter valid numbers.");

});

subtractButton.setOnAction(e -> {

try {

double num1 = Double.parseDouble(numberField1.getText());

double num2 = Double.parseDouble(numberField2.getText());

double result = num1 - num2;

resultLabel.setText("Result: " + result);

} catch (NumberFormatException ex) {

resultLabel.setText("Please enter valid numbers.");

});

multiplyButton.setOnAction(e -> {

try {

double num1 = Double.parseDouble(numberField1.getText());

double num2 = Double.parseDouble(numberField2.getText());

double result = num1 * num2;


resultLabel.setText("Result: " + result);

} catch (NumberFormatException ex) {

resultLabel.setText("Please enter valid numbers.");

});

divideButton.setOnAction(e -> {

try {

double num1 = Double.parseDouble(numberField1.getText());

double num2 = Double.parseDouble(numberField2.getText());

if (num2 == 0) {

resultLabel.setText("Cannot divide by zero.");

} else {

double result = num1 / num2;

resultLabel.setText("Result: " + result);

} catch (NumberFormatException ex) {

resultLabel.setText("Please enter valid numbers.");

});

// Create the scene with the layout

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

// Set up the stage (window)


primaryStage.setScene(scene);

primaryStage.setTitle("Simple Calculator");

primaryStage.show();

public static void main(String[] args) {

launch(args);

You might also like