Introduction
Shopping cart systems are a fundamental feature of any e-commerce platform. They allow customers to add items to their cart and proceed to checkout to purchase those items. Our shopping cart system will allow users to add and remove items from their cart, view the total price of all items, and perform a checkout operation to finalize their purchase.
JavaFX is a popular framework for building desktop applications in Java, and it provides a variety of features and tools for developers to create rich and dynamic user interfaces. One of the key features of JavaFX is its support for data binding, a powerful mechanism for synchronizing the state of user interface components with the state of underlying data models.
In JavaFX, binding allows developers to create relationships between properties of different objects, such that changes in one property automatically propagate to the other. This can simplify the code required to handle updates and ensure that the user interface always reflects the current state of the application’s data.
In this article, we will explore the concept of binding in JavaFX by building a simple shopping cart system. We will use binding to keep track of the total price of the items in the cart and to update the cart display when items are added, removed, or cleared. We will also discuss some of the challenges associated with completing this app.
About the Code
private static final String BOOK_FILE = "BookPrices.txt";
bookListView = new ListView<>();
BufferedReader reader = new BufferedReader(new FileReader(BOOK_FILE));
String entry;
while((entry = reader.readLine()) != null)
{
String[] bookEntry = entry.split(", ");
String bookTitle = bookEntry[0];
double bookPrice = Double.parseDouble(bookEntry[1]);
bookListView.getItems().add(bookTitle + " - $" + bookPrice);
}
reader.close();
This code segment is responsible for reading book titles and their corresponding prices from a text file named “BookPrices.txt” and populating them into a JavaFX ListView object named “bookListView”.
Here’s a brief explanation of each line of code:
private static final String BOOK_FILE = "BookPrices.txt";
– This line declares a constant variable “BOOK_FILE” with the value “BookPrices.txt”, which is the name of the text file that contains the book titles and prices.bookListView = new ListView<>();
– This line initializes a new empty ListView object named “bookListView” that will be used to display the book titles and prices.BufferedReader reader = new BufferedReader(new FileReader(BOOK_FILE));
– This line creates a BufferedReader object named “reader” and initializes it with a new FileReader object that reads the contents of the text file specified by the “BOOK_FILE” constant.String entry;
– This line declares a String variable “entry” that will be used to store each line of text read from the file.while((entry = reader.readLine()) != null)
– This line reads each line of text from the text file until there are no more lines to read. The read line is stored in the “entry” variable.String[] bookEntry = entry.split(", ");
– This line splits the read line into an array of strings using the delimiter “, ” and stores it in a String array named “bookEntry”.String bookTitle = bookEntry[0];
– This line assigns the first element of the “bookEntry” array, which is the book title, to a String variable “bookTitle”.double bookPrice = Double.parseDouble(bookEntry[1]);
– This line assigns the second element of the “bookEntry” array, which is the book price, to a double variable “bookPrice” after parsing it from a String to a double.bookListView.getItems().add(bookTitle + " - $" + bookPrice);
– This line appends each book title and its corresponding price, formatted as a string, to the “bookListView” object.reader.close();
– This line closes the file reader after reading all the lines from the file.
// Add to Cart
Button addButton = new Button("Add to Cart");
addButton.setOnAction(event ->
{
String selectedBook = bookListView.getSelectionModel().getSelectedItem();
if(selectedBook != null)
{
String[] bookItem = selectedBook.split(" - \\$");
String bookTitle = bookItem[0];
double bookPrice = Double.parseDouble(bookItem[1]);
int quantity = 1;
String cartItem = bookTitle + " (x" + quantity + ") - $" + (bookPrice * quantity);
cartListView.getItems().add(cartItem);
totalPrice.set(totalPrice.get() + bookPrice * quantity);
}
});
The addButton
is a Button
object that, when clicked, adds the selected book from the bookListView
to the cartListView
. The selected book is obtained from the bookListView
by calling the getSelectedItem
method, which returns the currently selected item. If a book is selected, its title, price, and quantity are used to create a cart item string, which is added to the cartListView
. The total price is updated by adding the price of the selected book multiplied by the quantity to the current value of the totalPrice
variable.
totalPriceLabel.textProperty().bind(Bindings.format("Total Price: $%.2f", totalPrice));
In this line of code, a binding is created between the textProperty
of the totalPriceLabel
label and a formatted string that includes the value of the totalPrice
variable.
The textProperty
represents the value of the text displayed in the label. By using the bind()
method of the textProperty
, any changes to the totalPrice
variable will automatically update the text displayed in the label.
The Bindings.format()
method is used to create a formatted string that includes the value of the totalPrice
variable. The string "Total Price: $%.2f"
specifies the format of the string, where %.2f
is a placeholder for a floating-point number with 2 decimal places.
Overall, this code ensures that the totalPriceLabel
always displays the current value of the totalPrice
variable, and keeps the display updated as the value of totalPrice
changes.
See my Full Code
See the App in Action
Challenges
Here are some possible challenges that could arise when implementing this shopping cart program:
- Reading the BookPrices.txt file: The code uses a BufferedReader to read the BookPrices.txt file, which could throw a FileNotFoundException or an IOException if the file is not found or if there is an error reading the file.
- Parsing the book prices: The book prices in the BookPrices.txt file are stored as strings with a dollar sign, which need to be parsed into double values in order to perform arithmetic operations. The code uses the Double.parseDouble() method to achieve this, but if the string is not in the correct format, a NumberFormatException could be thrown.
- Updating the total price: The program needs to keep track of the total price of the items in the shopping cart. The code uses a DoubleProperty and binds it to a Label to display the total price. However, updating the total price can be a challenge, as it involves performing arithmetic operations on double values, which can sometimes result in precision errors.
- Adding and removing items from the cart: The program allows users to add and remove items from the shopping cart. The code uses ListView objects to display the book items and cart items, and the add and remove buttons update these lists accordingly. However, removing an item from the middle of the cart list can be tricky, as it requires updating the indices of the remaining items in the list.
- Handling edge cases: There are several edge cases that the program needs to handle, such as selecting an item from the book list or cart list before clicking the add or remove button, removing an item from an empty cart, and adding negative quantities of items to the cart. These edge cases require additional error checking and input validation to ensure that the program runs smoothly.
Conclusion
In conclusion, creating a simple bookstore program in Java involves several crucial steps, including file I/O, implementing a GUI, and managing data structures. By using JavaFX and the various classes and libraries provided by the language, we were able to create a functional and user-friendly bookstore program that allows customers to view and purchase books. The use of binding in the GUI components also helped to keep the interface up-to-date with the underlying data, making it more responsive and user-friendly. Overall, this project highlights the importance of proper design and implementation when creating software applications, particularly those involving user interfaces and data management.
Reference
T. Gaddis and G. Muganda, Starting Out with Java – From Control Structures through Data Structures, 4th Edition, 330 Hudson Street, NY NY 10013: Pearson, 2019.