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

Final JavaFX

Uploaded by

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

Final JavaFX

Uploaded by

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

IITU

Report

Final: Introduction To Programming

Name: Tabachnaya Sanilya, Anvar


Mussirep, Zhaniya Yerkinbek
Group: IT3-2406DS
1. Introduction:

This project is a Chocolate Store application developed

using JavaFX.

2. Project Title: Online Chocolate Store


Description: Project provides an interactive
and user-friendly interface for managing a
virtual chocolate store. Users can browse a
list of chocolate products, add items to their
shopping cart, view their cart's contents
with images, and proceed to purchase
selected items.

3. Objective:

The aim of this project is to develop a to develop a


functional and user-friendly desktop application for
managing a virtual chocolate store. The application
provides an intuitive interface for users to explore a variety
of chocolate products, add them to their shopping cart,
view and manage their selected items, and complete
purchases seamlessly.
The application will allow users to:

Browse Products:

 View a list of available chocolate products,


each accompanied by an image, name, and
price.

 Quickly identify products through a visually


appealing interface.

Add Products to the Cart:

 Add items directly to the cart using a


convenient button located next to each
product.

 Update quantities automatically when the


same product is added multiple times.

Manage the Shopping Cart:

 Remove individual products or decrease


their quantities within the cart.

 Clear the entire cart with a single action


when needed.

Complete Purchases:

 Select specific items from the cart and


proceed to buy them.

 Receive confirmation messages for


successful transactions.
View Total Costs Dynamically:

 Track the total price of all items in the cart,


updated dynamically as changes are made.

4. Application window:

5. Features of the Project:

a. User-Friendly Interface:

 Visually appealing design with images, labels, and


dynamic price updates.
 Easy navigation through products and cart
functionalities.
 Interactive buttons positioned logically for intuitive
user interactions.
b. Task Management:
 Allows users to browse a catalog of chocolate
products.
 Supports adding products to a shopping cart with
automated quantity updates.
 Provides functionality to remove items, adjust
quantities, and clear the cart.
 Enables seamless product purchase and
confirmation.
c. Data Persistence:

 Maintains a predefined catalog of products with


images and prices.
 Displays cart items dynamically without requiring a
refresh.
 Updates the UI in real-time as items are added,
removed, or purchased.
d. Error Handling:

 Ensures robust handling of invalid user actions, such


as attempting to remove items from an empty cart.
 Provides clear alerts and feedback messages for key
actions like purchases or invalid operations.
 Prevents crashes or unexpected behavior by
validating user inputs and selections.
6. Technology Stack

 Programming Language: Java

 Framework: JavaFX (for graphical user


interface)

 IDE: IntelliJ IDEA


 Build Tool: Maven

7. Implementation Steps
1. Setting Up the Project:

 Install and configure the necessary tools: JDK,


JavaFX SDK, and Maven.
 Create a new Maven project and set up the pom.xml
file with the required dependencies for JavaFX.
 Organize the project structure, ensuring folders for
resources (e.g., src/main/resources) and source code
(e.g., src/main/java) are properly set.

2. Designing the GUI:

 Use FXML to design the graphical interface of the


application.
 Create views for displaying the list of products, the
shopping cart, and buttons for actions (e.g., add,
remove, buy).
 Style the application using JavaFX CSS to make it
visually appealing.
3. Writing the Logic:

 Implement the Product and HelloController


classes for managing data and user interactions.
 Write methods for adding products to the cart,
removing them, and calculating the total price.
 Use observable lists and bindings to dynamically
update the GUI when data changes.
4. Testing and Debugging:
 Test each feature of the application to ensure correct
functionality.
 Debug any issues that arise during interaction with
the GUI or logic implementation.
 Validate edge cases, such as adding duplicate items
or handling an empty cart.

8. Code :

hello-view.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.VBox?>

<VBox xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"


fx:controller="com.example.demo.HelloController"
style="-fx-padding: 20; -fx-spacing: 10; -fx-font-family: 'Roboto'; -fx-background-color: #f7f7f7;">

<!-- Заголовок для продуктов -->


<Label text="Продукты"
style="-fx-font-size: 16px; -fx-text-fill: #333333; -fx-font-weight: bold;"/>

<!-- Список продуктов -->


<ListView fx:id="productListView"
style="-fx-border-color: #dddddd; -fx-border-radius: 5; -fx-background-color: #ffffff; -fx-padding: 5;"/>

<!-- Заголовок для корзины -->


<Label text="Корзина"
style="-fx-font-size: 16px; -fx-text-fill: #333333; -fx-font-weight: bold;"/>

<!-- Список корзины -->


<ListView fx:id="cartListView"
style="-fx-border-color: #dddddd; -fx-border-radius: 5; -fx-background-color: #ffffff; -fx-padding: 5;"/>

<!-- Общая сумма -->


<Label fx:id="totalPriceLabel" text="Общая сумма: 0 тг"
style="-fx-font-size: 14px; -fx-text-fill: #333333; -fx-font-weight: normal;"/>

<!-- Кнопки действий -->


<VBox style="-fx-spacing: 8;">
<Button text="Добавить в корзину" onAction="#addToCart"
style="-fx-background-color: #0078d7; -fx-text-fill: white; -fx-font-size: 14px; -fx-background-radius: 5;"/>
<Button text="Очистить корзину" onAction="#clearCart"
style="-fx-background-color: #0078d7; -fx-text-fill: white; -fx-font-size: 14px; -fx-background-radius: 5;"/>
<Button text="Купить выбранное" onAction="#buySelectedProduct"
style="-fx-background-color: #0078d7; -fx-text-fill: white; -fx-font-size: 14px; -fx-background-radius: 5;"/>
<Button text="Купить всё" onAction="#buyAllProducts"
style="-fx-background-color: #0078d7; -fx-text-fill: white; -fx-font-size: 14px; -fx-background-radius: 5;"/>
</VBox>

</VBox>

HelloController.java:
package com.example.demo;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

import java.util.LinkedHashMap;
import java.util.Map;

public class HelloController {

@FXML
private ListView<Product> productListView;

@FXML
private ListView<Product> cartListView;

@FXML
private Label totalPriceLabel;

private ObservableList<Product> products = FXCollections.observableArrayList();


private Map<Product, Integer> cart = new LinkedHashMap<>();

@FXML
public void initialize() {

products.addAll(
new Product("Snickers", 280, "/images/snickers.jpg"),
new Product("Twix", 280, "/images/twix.jpg"),
new Product("Kazakhstan", 754, "/images/kazakhstan.jpg"),
new Product("Kinder Bueno", 418, "/images/kinder-bueno.jpg"),
new Product("Milka", 910, "/images/milka.jpg"),
new Product("Lindt", 1609, "/images/lindt.jpg"),
new Product("Kit-Kat", 350, "/images/kit_kat.jpg"),
new Product("Albeni", 250, "/images/albeni.jpg"),
new Product("Alpen Gold", 450, "/images/alpen_gold.jpg"),
new Product("MilkyWay", 159, "/images/milkyway.jpg"),
new Product("Toblerone", 1700, "/images/toblerone.jpg"),
new Product("Bounty", 280, "/images/bounty.jpg"),
new Product("Picnic", 366, "/images/picnic.jpg"),
new Product("Roshen", 652, "/images/roshen.jpg"),
new Product("Nestle", 600, "/images/nestle.jpg")
);

configureProductListView();
configureCartListView();

productListView.setItems(products);
updateCartListView();
}

private void configureProductListView() {


productListView.setCellFactory(param -> new ListCell<>() {
private final ImageView imageView = new ImageView();

@Override
protected void updateItem(Product item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
} else {
setText(item.getName() + " (" + item.getPrice() + " тг)");
try {
imageView.setImage(item.getImage());
} catch (Exception e) {
System.err.println("Ошибка загрузки изображения: " + item.getImagePath());
imageView.setImage(null);
}
imageView.setFitWidth(50);
imageView.setFitHeight(50);
setGraphic(imageView);
}
}
});
}

private void configureCartListView() {


cartListView.setCellFactory(param -> new ListCell<>() {
private final ImageView imageView = new ImageView();
private final Button increaseButton = new Button("+");
private final Button decreaseButton = new Button("-");

@Override
protected void updateItem(Product product, boolean empty) {
super.updateItem(product, empty);
if (empty || product == null) {
setText(null);
setGraphic(null);
} else {
int quantity = cart.getOrDefault(product, 0);
int subtotal = product.getPrice() * quantity;

setText(product.getName() + " x" + quantity + " (" + subtotal + " тг)");

try {
imageView.setImage(product.getImage());
} catch (Exception e) {
System.err.println("Ошибка загрузки изображения: " + product.getImagePath());
imageView.setImage(null);
}
imageView.setFitWidth(50);
imageView.setFitHeight(50);

increaseButton.setOnAction(event -> increaseQuantity(product));


decreaseButton.setOnAction(event -> decreaseQuantity(product));

setGraphic(new javafx.scene.layout.HBox(imageView, increaseButton, decreaseButton));


}
}
});
}

private void updateCartListView() {


ObservableList<Product> cartItems = FXCollections.observableArrayList(cart.keySet());
cartListView.setItems(cartItems);

int totalPrice = cart.entrySet().stream()


.mapToInt(entry -> entry.getKey().getPrice() * entry.getValue())
.sum();
totalPriceLabel.setText("Общая сумма: " + totalPrice + " тг");
}

@FXML
public void addToCart() {
Product selectedProduct = productListView.getSelectionModel().getSelectedItem();
if (selectedProduct != null) {
cart.put(selectedProduct, cart.getOrDefault(selectedProduct, 0) + 1);
updateCartListView();
}
}

@FXML
public void removeFromCart() {
Product selectedProduct = cartListView.getSelectionModel().getSelectedItem();
if (selectedProduct != null) {
int quantity = cart.getOrDefault(selectedProduct, 0);
if (quantity > 1) {
cart.put(selectedProduct, quantity - 1);
} else {
cart.remove(selectedProduct);
}
updateCartListView();
}
}

@FXML
public void clearCart() {
cart.clear();
updateCartListView();
}

@FXML
public void buySelectedProduct() {
Product selectedProduct = cartListView.getSelectionModel().getSelectedItem();
if (selectedProduct != null) {
int quantity = cart.getOrDefault(selectedProduct, 0);
int subtotal = selectedProduct.getPrice() * quantity;
// Удаляем товар из корзины
cart.remove(selectedProduct);
updateCartListView();

// Показ уведомления с информацией о купленном товаре


Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Покупка товара");
alert.setHeaderText(null);
alert.setContentText("Вы успешно купили:\n" +
selectedProduct.getName() + " x" + quantity + "\n" +
"Общая цена: " + subtotal + " тг");
alert.showAndWait();
} else {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Ошибка");
alert.setHeaderText(null);
alert.setContentText("Выберите товар для покупки!");
alert.showAndWait();
}
}

@FXML
public void buyAllProducts() {
if (!cart.isEmpty()) {
// Создаем сообщение о купленных товарах
StringBuilder receipt = new StringBuilder("Вы успешно купили:\n");

int totalPrice = 0;
for (Map.Entry<Product, Integer> entry : cart.entrySet()) {
Product product = entry.getKey();
int quantity = entry.getValue();
int subtotal = product.getPrice() * quantity;

receipt.append(product.getName())
.append(" x")
.append(quantity)
.append(" (")
.append(subtotal)
.append(" тг)\n");

totalPrice += subtotal;
}

// Добавляем общую сумму в сообщение


receipt.append("\nОбщая сумма: ").append(totalPrice).append(" тг");

// Очистка корзины
cart.clear();
updateCartListView();

// Показ уведомления с информацией о купленных товарах


Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Покупка всей корзины");
alert.setHeaderText(null);
alert.setContentText(receipt.toString());
alert.showAndWait();
} else {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Ошибка");
alert.setHeaderText(null);
alert.setContentText("Корзина пуста! Добавьте товары для покупки.");
alert.showAndWait();
}
}

private void increaseQuantity(Product product) {


cart.put(product, cart.getOrDefault(product, 0) + 1);
updateCartListView();
}

private void decreaseQuantity(Product product) {


int quantity = cart.getOrDefault(product, 0);
if (quantity > 1) {
cart.put(product, quantity - 1);
} else {
cart.remove(product);
}
updateCartListView();
}
}

HelloApplication.java:
package com.example.demo;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application {


@Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 550, 300);
stage.setTitle("Chocolate");
stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {


launch();
}
}

Product.java:
package com.example.demo;

import javafx.scene.image.Image;
import java.util.Objects;
public class Product {
private String name;
private int price;
private String imagePath;

public Product(String name, int price, String imagePath) {


this.name = name;
this.price = price;
this.imagePath = imagePath;
}

public String getName() {


return name;
}

public int getPrice() {


return price;
}

public String getImagePath() {


return imagePath;
}
// public int getQuantity(){
//
// }

public Image getImage() {


return new Image(Product.class.getResourceAsStream(imagePath));
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
return Objects.equals(name, product.name);
}

@Override
public int hashCode() {
return Objects.hash(name);
}
}

9. Challenges Faced:

1. Adding photos to a shared product list and cart.


2. Difficulties in setting up the correct display of images
in the product list and cart.
3. Issues with using relative paths for images and
resources.
4. Excessively dense arrangement of interface elements,
which made navigation difficult.
5. Difficulties in writing formulas for finding the total
amount and the amount of an individual product

10. Conclusion:

This JavaFX-based application demonstrates how to create


a simple and interactive virtual store. Users can browse
products, add them to a shopping cart, and complete
purchases. The app uses JavaFX components for an easy-
to-navigate interface and updates the cart dynamically as
items are added or removed. This project is a great
learning tool for understanding JavaFX, FXML, and
resource management. It can also serve as a starting point
for more complex applications, such as e-commerce
platforms.

You might also like