Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

import java.io.

*;

import javax.swing.*;

import java.awt.event.*;

import java.util.ArrayList;

class Car {

private String brand;

private String model;

private int year;

public Car(String brand, String model, int year) {

this.brand = brand;

this.model = model;

this.year = year;

public String getBrand() {

return brand;

public String getModel() {

return model;

public int getYear() {

return year;

@Override
public String toString() {

return brand + " " + model + " (" + year + ")";

class CarRental {

private ArrayList<Car> cars;

public CarRental() {

cars = new ArrayList<>();

public void addCar(Car car) {

cars.add(car);

public void removeCar(int index) {

cars.remove(index);

public ArrayList<Car> getCars() {

return cars;

class CarRentalGUI extends JFrame {

private CarRental carRental;

private JComboBox<String> carList;


public CarRentalGUI(CarRental carRental) {

this.carRental = carRental;

JLabel label = new JLabel("Select a car:");

carList = new JComboBox<>();

JButton rentButton = new JButton("Rent");

JButton returnButton = new JButton("Return");

for (Car car : carRental.getCars()) {

carList.addItem(car.toString());

rentButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

int index = carList.getSelectedIndex();

if (index >= 0) {

carRental.removeCar(index);

updateCarList();

});

returnButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String brand = JOptionPane.showInputDialog("Enter car brand:");

String model = JOptionPane.showInputDialog("Enter car model:");

int year = Integer.parseInt(JOptionPane.showInputDialog("Enter car year:"));

carRental.addCar(new Car(brand, model, year));

updateCarList();
}

});

setLayout(new FlowLayout());

add(label);

add(carList);

add(rentButton);

add(returnButton);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

pack();

setVisible(true);

private void updateCarList() {

carList.removeAllItems();

for (Car car : carRental.getCars()) {

carList.addItem(car.toString());

public class CarRentalSystem {

public static void main(String[] args) {

CarRental carRental = new CarRental();

carRental.addCar(new Car("Toyota", "Camry", 2020));

carRental.addCar(new Car("Honda", "Accord", 2019));

carRental.addCar(new Car("Ford", "Mustang", 2021));


CarRentalGUI gui = new CarRentalGUI(carRental);

You might also like