×
Samples Blogs Make Payment About Us Reviews 4.9/5 Order Now

Building a Java Vehicle Rental System with GUI : Step-by-Step Guide

June 14, 2024
Sofiya Marcus
Sofiya Marcus
🇬🇧 United Kingdom
Java
PhD-qualified in Computer Science from the University of Bolton, I am Sofiya Marcus, a Java assignment expert with 7 years of experience. I specialize in delivering high-quality, tailored solutions for complex programming tasks.
Tip of the day
Familiarize yourself with OCaml's pattern matching; it simplifies handling recursive data structures like lists and trees, making your code concise and easier to debug.
News
In 2024, Girls Who Code introduced a Data Science + AI track in their free summer programs for high school students, fostering skills in cybersecurity and creative coding​
Key Topics
  • Creating Java Vehicle Rental System
  • Block 1: `Main` Class
  • Block 2: Import Statements
  • Block 3: `MainGUI` Class
  • Block 4: `initGUI` Method
  • Block 5: `loadVehicleTable` Method
  • Block 6: `RefreshButtonActionListener` Class
  • Block 7: `BookButtonActionListener` Class
  • Block 8: `RentalSlotDialog` Class
  • Block 9: `CalculateButtonActionListener` Class
  • Block 10: `main` Method in `MainGUI` Class
  • Block 11: `Car` Class
  • Block 12: `Motorbike` Class
  • Block 13: `RentalManager` Interface
  • Block 14: `RentalSlot` Class
  • Block 15: `Vehicle` Class
  • Conclusion

In this guide, you will learn how to create a Java program that manages vehicle rentals with a graphical user interface (GUI). This project is designed to help you understand and implement a real-world application involving user interaction, data management, and calculations. By the end of this guide, you will have a Java program that allows users to view available vehicles, refresh the list of vehicles, and book rental slots. Additionally, the program calculates rental costs and applies discounts based on rental duration. Whether you're a beginner looking to build your programming skills or an experienced developer exploring Java GUI applications, this guide provides valuable insights into designing and building an interactive vehicle rental management system.

Creating Java Vehicle Rental System

Explore our comprehensive guide on building a Java vehicle rental management program with a GUI. Whether you're a beginner or an experienced programmer, this guide offers valuable insights into Java GUI development, providing essential help with your Java assignment. Learn to create interactive vehicle rental systems step by step and gain the skills to design and develop user-friendly software applications for various real-world scenarios. This project equips you with the knowledge needed to customize and extend interactive systems, making it a valuable asset for your programming journey.

Block 1: `Main` Class

```java public class Main { public static void main(String[] args) { WestminsterSkinConsultationManager manager = new WestminsterSkinConsultationManager(); manager.run(); } } ```

This block contains the main class that serves as the entry point of the program. It creates an instance of `WestminsterSkinConsultationManager` and runs its `run` method. This is the starting point of the program.

Block 2: Import Statements

```java import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; ```

These import statements bring in necessary classes and packages, including GUI components and utilities for working with dates and lists.

Block 3: `MainGUI` Class

```java import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class MainGUI extends JFrame { private WestminsterSkinConsultationManager consultationManager; // an instance of WestminsterSkinConsultationManager private List vehicles; // a list of available vehicles private JTable vehicleTable; // a table to display the available vehicles private DefaultTableModel vehicleTableModel; // a table model for the vehicle table public MainGUI(WestminsterSkinConsultationManager consultationManager) { this.consultationManager = consultationManager; this.vehicles = new ArrayList<>(consultationManager.getAvailableVehicles()); initGUI(); } private void initGUI() { setTitle("Westminster Skin Consultation Centre"); setSize(800, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); // create the vehicle table and add it to a scroll pane vehicleTableModel = new DefaultTableModel(new Object[]{"Type", "Plate", "Make", "Details"}, 0); vehicleTable = new JTable(vehicleTableModel); JScrollPane jScrollPane = new JScrollPane(vehicleTable); add(jScrollPane, BorderLayout.CENTER); // create a panel for the buttons and add the refresh and book buttons JPanel buttonsPanel = new JPanel(new FlowLayout()); JButton refreshButton = new JButton("Refresh"); refreshButton.addActionListener(new RefreshButtonActionListener()); buttonsPanel.add(refreshButton); JButton bookButton = new JButton("Book Slot"); bookButton.addActionListener(new BookButtonActionListener()); buttonsPanel.add(bookButton); add(buttonsPanel, BorderLayout.SOUTH); // load the vehicle table with data loadVehicleTable(); } // Rest of the MainGUI class code (omitted for brevity) // ... } ```

This block defines the `MainGUI` class, which extends `JFrame` to create the graphical user interface for managing vehicle rentals. The class includes instance variables, a constructor, and methods for initializing the GUI and managing vehicle data.

Block 4: `initGUI` Method

```java private void initGUI() { setTitle("Westminster Skin Consultation Centre"); setSize(800, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); // create the vehicle table and add it to a scroll pane vehicleTableModel = new DefaultTableModel(new Object[]{"Type", "Plate", "Make", "Details"}, 0); vehicleTable = new JTable(vehicleTableModel); JScrollPane jScrollPane = new JScrollPane(vehicleTable); add(jScrollPane, BorderLayout.CENTER); // create a panel for the buttons and add the refresh and book buttons JPanel buttonsPanel = new JPanel(new FlowLayout()); JButton refreshButton = new JButton("Refresh"); refreshButton.addActionListener(new RefreshButtonActionListener()); buttonsPanel.add(refreshButton); JButton bookButton = new JButton("Book Slot"); bookButton.addActionListener(new BookButtonActionListener()); buttonsPanel.add(bookButton); add(buttonsPanel, BorderLayout.SOUTH); // load the vehicle table with data loadVehicleTable(); } ```

This method initializes the GUI by setting the frame's properties, creating a table to display vehicle information, adding buttons for refreshing and booking slots, and loading data into the table.

Block 5: `loadVehicleTable` Method

```java private void loadVehicleTable() { // Clear the existing rows from the table model vehicleTableModel.setRowCount(0); // Sort the list of vehicles by license plate vehicles.sort((v1, v2) -> v1.getPlate().compareToIgnoreCase(v2.getPlate())); // Add each vehicle to the table model for (Vehicle vehicle : vehicles) { if (vehicle instanceof Car) { Car car = (Car) vehicle; vehicleTableModel.addRow(new Object[]{"Car", car.getPlate(), car.getMake(), "Engine: " + car.getEngineType() + ", Doors: " + car.getNumOfDoors()}); } else if (vehicle instanceof Motorbike) { Motorbike motorbike = (Motorbike) vehicle; vehicleTableModel.addRow(new Object[]{"Motorbike", motorbike.getPlate(), motorbike.getMake(), "Seats: " + motorbike.getNumOfSeats() + ", Engine Size: " + motorbike.getEngineSize()}); } } } ```

This method is responsible for loading vehicle data into the table. It clears existing rows, sorts the list of vehicles, and adds each vehicle to the table model. It differentiates between cars and motorbikes when displaying vehicle details.

Block 6: `RefreshButtonActionListener` Class

```java // Listener for the refresh button private class RefreshButtonActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // Update the list of vehicles and reload the table vehicles = new ArrayList<>(consultationManager.getAvailableVehicles()); loadVehicleTable(); } } ```

This inner class defines an action listener for the "Refresh" button. When the button is clicked, it updates the list of available vehicles and reloads the table.

Block 7: `BookButtonActionListener` Class

```java // Listener for the book button private class BookButtonActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // Get the selected vehicle from the table and show a rental slot dialog int selectedRow = vehicleTable.getSelectedRow(); if (selectedRow >= 0) { Vehicle vehicle = vehicles.get(selectedRow); RentalSlotDialog rentalSlotDialog = new RentalSlotDialog(vehicle); rentalSlotDialog.setVisible(true); } else { JOptionPane.showMessageDialog(MainGUI.this, "Please select a vehicle to book a slot."); } } } ```

This inner class defines an action listener for the "Book Slot" button. It allows users to select a vehicle from the table and open a dialog for booking a rental slot.

Block 8: `RentalSlotDialog` Class

```java // Dialog for booking a rental slot private class RentalSlotDialog extends JDialog { private Vehicle vehicle; private JTextField pickupDateField; private JTextField dropoffDateField; public RentalSlotDialog(Vehicle vehicle) { this.vehicle = vehicle; setTitle("Book a Slot: " + vehicle.getMake() + " " + vehicle.getPlate()); setSize(700, 500); setLayout(new GridLayout(3, 2); // Add fields for the pick-up and drop-off dates and times add(new JLabel("Pick-up Date & Time (dd/MM/yyyy HH:mm):")); pickupDateField = new JTextField(); add(pickupDateField); add(new JLabel("Drop-off Date & Time (dd/MM/yyyy HH:mm):")); dropoffDateField = new JTextField(); add(dropoffDateField); // Add buttons for canceling or booking the rental slot JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(e -> dispose()); add(cancelButton); JButton calculateButton = new JButton("Calculate & Book"); calculateButton.addActionListener(new CalculateButtonActionListener()); add(calculateButton); } // Listener for the calculate and book button private class CalculateButtonActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // Handle booking calculations and validations // ... } } } ```

This inner class represents a dialog for booking a rental slot. It includes fields for entering pickup and drop-off dates and times, along with buttons for canceling or booking the slot.

Block 9: `CalculateButtonActionListener` Class

```java // Listener for the calculate and book button private class CalculateButtonActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { try { // Parse the pick-up and drop-off dates and times SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm"); Date pickupDate = dateFormat.parse(pickupDateField.getText()); Date dropoffDate = dateFormat.parse(dropoffDateField.getText()); // Check that the drop-off date is after the pick-up date if (dropoffDate.before(pickupDate)) { JOptionPane.showMessageDialog(RentalSlotDialog.this, "Drop-off date must be after pick-up date."); return; } // Check if the vehicle can be booked for the given time slot if (!vehicle.canBeBooked(pickupDate, dropoffDate)) { JOptionPane.showMessageDialog(RentalSlotDialog.this, "This Vehicle cannot be booked in this slot. Please select some other timings."); return; } // Calculate the cost of the rental slot double hours = (dropoffDate.getTime() - pickupDate.getTime()) / 3600000.0; double pricePerHour = vehicle instanceof Car ? 20 : 10; double cost = hours * pricePerHour; double discount = 0; // Apply a discount based on the duration of the rental if (hours > 72) { discount = cost * 0.1; } else if (hours > 48) { discount = cost * 0.05; } double finalCost = cost - discount; // Show a confirmation dialog with the cost, discount, and total int result = JOptionPane.showConfirmDialog( RentalSlotDialog.this, String.format( "Cost: £%.2f\nDiscount: £%.2f\nTotal: £%.2f\n\nConfirm booking?", cost, discount, finalCost ), "Booking Confirmation", JOptionPane.YES_NO_OPTION ); // If the user confirms the booking, set the rental slot for the vehicle and show a success message if (result == JOptionPane.YES_OPTION) { RentalSlot rentalSlot = new RentalSlot(pickupDate, dropoffDate); vehicle.setRentalSlot(rentalSlot); JOptionPane.showMessageDialog( RentalSlotDialog.this, "Booking successful. Thank you for using Westminster Skin Consultation Centre." ); dispose(); } } catch (ParseException ex) { JOptionPane.showMessageDialog( RentalSlotDialog.this, "Invalid date format. Please use the format: dd/MM/yyyy HH:mm." ); } } } ```

This inner class defines an action listener for the "Calculate & Book" button within the `RentalSlotDialog`. It handles the calculation of the cost for the rental slot, applies discounts, and confirms the booking.

Block 10: `main` Method in `MainGUI` Class

```java public static void main(String[] args) { WestminsterSkinConsultationManager consultationManager = new WestminsterSkinConsultationManager(); MainGUI mainGUI = new MainGUI(consultationManager); mainGUI.setVisible(true); } ```

This is a `main` method that creates an instance of `WestminsterSkinConsultationManager` and `MainGUI`, setting the GUI visible for user interaction.

Block 11: `Car` Class

```java public class Car extends Vehicle { private String engineType; private int numOfDoors; public Car(String plate, String make, String engineType, int numOfDoors) { super(plate, make); this.engineType = engineType; this.numOfDoors = numOfDoors; } public String getEngineType() { return engineType; } public void setEngineType(String engineType) { this.engineType = engineType; } public int getNumOfDoors() { return numOfDoors; } public void setNumOfDoors(int numOfDoors) { this.numOfDoors = numOfDoors; } } ```

This block defines the `Car` class, which extends the `Vehicle` class. It includes properties like `engineType` and `numOfDoors`, along with getter and setter methods.

Block 12: `Motorbike` Class

```java public class Motorbike extends Vehicle { private int numOfSeats; private int engineSize; public Motorbike(String plate, String make, int numOfSeats, int engineSize) { super(plate, make); this.numOfSeats = numOfSeats; this engineSize = engineSize; } public int getNumOfSeats() { return numOfSeats; } public void setNumOfSeats(int numOfSeats) { this.numOfSeats = numOfSeats; } public int getEngineSize() { return engineSize; } public void setEngineSize(int engineSize) { this.engineSize = engineSize; } } ```

This block defines the `Motorbike` class, which also extends the `Vehicle` class. It includes properties like `numOfSeats` and `engineSize`, along with getter and setter methods.

Block 13: `RentalManager` Interface

```java import java.util.List; interface RentalManager { void addVehicle(Vehicle vehicle); void removeVehicle(Vehicle vehicle); List getAvailableVehicles(); } ```

This block defines the `RentalManager` interface, which includes methods for adding and removing vehicles and retrieving available vehicles.

Block 14: `RentalSlot` Class

```java import java.util.Date; public class RentalSlot { private Date pickupDateTime; private Date dropoffDateTime; public RentalSlot(Date pickupDateTime, Date dropoffDateTime) { this.pickupDateTime = pickupDateTime; this.dropoffDateTime = dropoffDateTime; } public Date getPickupDateTime() { return pickupDateTime; } public void setPickupDateTime(Date pickupDateTime) { this.pickupDateTime = pickupDateTime; } public Date getDropoffDateTime() { return dropoffDateTime; } public void setDropoffDateTime(Date dropoffDateTime) { this.dropoffDateTime = dropoffDateTime; } } ```

This block defines the `RentalSlot` class, representing a rental slot with pickup and drop-off date-time properties.

Block 15: `Vehicle` Class

```java import java.util.Date; abstract class Vehicle { private String plate; private String make; private RentalSlot rentalSlot; public Vehicle(String plate, String make) { this.plate = plate; this.make = make; this.rentalSlot = null; } public String getPlate() { return plate; } public void setPlate(String plate) { this.plate = plate; } public String getMake() { return make; } public void setMake(String make) { this.make = make; } public void setRentalSlot(RentalSlot slot){ this.rentalSlot = slot; } public RentalSlot getRentalSlot(){ return rentalSlot; } public boolean canBeBooked(Date pickupDate, Date dropoffDate) { if (rentalSlot == null) { return true; } Date currentPickupDate = rentalSlot.getPickupDateTime(); Date currentDropoffDate = rentalSlot.getDropoffDateTime(); // Check if the specified pickup date is after the current drop-off date if (pickupDate.after(currentDropoffDate)) { return true; } // Check if the specified drop-off date is before the current pickup date if (dropoffDate.before(currentPickupDate)) { return true; } // Otherwise, the vehicle is not available during the specified rental period return false; } } ```

This block defines the abstract `Vehicle` class, which includes properties like `plate`, `make`, and `rentalSlot`, along with methods for checking if a vehicle can be booked.

Conclusion

This Java program for managing vehicle rentals with a GUI is a versatile and practical solution for businesses in the vehicle rental industry. It allows users to interact with a user-friendly interface, book rental slots, and calculates costs with discounts. You can adapt and enhance this program to meet specific business needs, making it a valuable tool for vehicle rental management. By implementing this project, you gain valuable experience in building interactive software applications, which can be extended and customized for various real-world applications. Whether you're managing a vehicle rental business or simply learning Java programming, this project equips you with the knowledge and skills needed to create sophisticated, user-friendly systems.

Similar samples

Dive into our curated collection of programming homework samples showcasing our proficiency across various languages and topics. These examples demonstrate our dedication to delivering clear, concise, and effective solutions. Explore them to gain insights into how we can assist you in achieving academic success with your programming assignments.