Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.BorderLayout;
- import java.awt.Color;
- import java.awt.Dimension;
- import java.awt.GridLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import javax.swing.BoxLayout;
- import javax.swing.JButton;
- import javax.swing.JComboBox;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JOptionPane;
- import javax.swing.JPanel;
- import javax.swing.JPasswordField;
- import javax.swing.JScrollPane;
- import javax.swing.JTable;
- import javax.swing.JTextField;
- import javax.swing.SwingConstants;
- import javax.swing.SwingUtilities;
- import javax.swing.border.EtchedBorder;
- import javax.swing.border.TitledBorder;
- import javax.swing.table.DefaultTableModel;
- class Book {
- private String title;
- private String author;
- private int quantity;
- private double price;
- private String genre;
- public Book(String title, String author, int quantity, double price, String genre) {
- this.title = title;
- this.author = author;
- this.quantity = quantity;
- this.price = price;
- this.genre = genre;
- }
- public String getTitle() {
- return title;
- }
- public String getAuthor() {
- return author;
- }
- public int getQuantity() {
- return quantity;
- }
- public void setQuantity(int quantity) {
- this.quantity = quantity;
- }
- public double getPrice() {
- return price;
- }
- public String getGenre() {
- return genre;
- }
- public void decreaseQuantity() {
- quantity--;
- }
- }
- class BookManager {
- private static BookManager instance;
- private List<Book> books;
- private BookManager() {
- books = new ArrayList<>();
- // Initialize with some sample books
- books.add(new Book("It", "Stephen King", 10, 15.99, "Fiction"));
- books.add(new Book("Sapiens", "Yuval Noah Harari", 5, 12.50, "Non-Fiction"));
- }
- public static BookManager getInstance() {
- if (instance == null) {
- instance = new BookManager();
- }
- return instance;
- }
- public List<Book> getAllBooks() {
- return books;
- }
- public void addBook(Book book) {
- books.add(book);
- }
- // New method to get books by genre
- public List<Book> getBooksByGenre(String genre) {
- List<Book> booksByGenre = new ArrayList<>();
- for (Book book : books) {
- if (book.getGenre().equalsIgnoreCase(genre) || genre.equalsIgnoreCase("All")) {
- booksByGenre.add(book);
- }
- }
- return booksByGenre;
- }
- public void updateBook(int index, Book updatedBook) {
- if (index >= 0 && index < books.size()) {
- books.set(index, updatedBook);
- } else {
- throw new IllegalArgumentException("Invalid book index");
- }
- }
- public void removeBook(int index) {
- if (index >= 0 && index < books.size()) {
- books.remove(index);
- } else {
- throw new IllegalArgumentException("Invalid book index");
- }
- }
- }
- // User class to represent a user
- class User {
- private String username;
- private String password;
- public User(String username, String password) {
- this.username = username;
- this.password = password;
- }
- public String getUsername() {
- return username;
- }
- public boolean validatePassword(String password) {
- return this.password.equals(password);
- }
- }
- // UserManager class to manage user authentication
- class UserManager {
- private static UserManager instance;
- private Map<String, User> users;
- private UserManager() {
- users = new HashMap<>();
- // Default admin user
- users.put("admin", new User("admin", "admin"));
- }
- public static UserManager getInstance() {
- if (instance == null) {
- instance = new UserManager();
- }
- return instance;
- }
- public boolean userExists(String username) {
- return users.containsKey(username);
- }
- public boolean addUser(String username, String password) {
- if (!userExists(username)) {
- users.put(username, new User(username, password));
- return true;
- }
- return false;
- }
- public boolean validateCredentials(String username, String password) {
- if (userExists(username)) {
- User user = users.get(username);
- return user.validatePassword(password);
- }
- return false;
- }
- }
- class Login extends JFrame {
- private JTextField usernameField;
- private JPasswordField passwordField;
- private JLabel errorLabel;
- private UserManager userManager;
- public Login() {
- userManager = UserManager.getInstance();
- setTitle("Login");
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setResizable(false);
- setSize(320, 150);
- setLocationRelativeTo(null); // Center the window on the screen
- JPanel panel = new JPanel();
- panel.setLayout(new GridLayout(3, 2, 5, 5));
- JLabel usernameLabel = new JLabel("Username:");
- panel.add(usernameLabel);
- usernameField = new JTextField();
- panel.add(usernameField);
- JLabel passwordLabel = new JLabel("Password:");
- panel.add(passwordLabel);
- passwordField = new JPasswordField();
- panel.add(passwordField);
- JButton loginButton = new JButton("Login");
- loginButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- login();
- }
- });
- panel.add(loginButton);
- errorLabel = new JLabel("");
- errorLabel.setForeground(Color.RED);
- panel.add(errorLabel);
- add(panel);
- setVisible(true);
- }
- private void login() {
- String username = usernameField.getText();
- String password = new String(passwordField.getPassword());
- if (userManager.validateCredentials(username, password)) {
- dispose();
- if (username.equals("admin")) {
- SwingUtilities.invokeLater(AdminPane::new);
- } else {
- SwingUtilities.invokeLater(OnlineBookStore::new);
- }
- } else {
- // Incorrect username or password
- errorLabel.setText("Invalid username or password.");
- usernameField.setText(""); // Clear username field
- passwordField.setText(""); // Clear password field
- }
- }
- }
- class SignUp extends JFrame {
- private JTextField usernameField;
- private JPasswordField passwordField;
- private JLabel errorLabel;
- private UserManager userManager;
- public SignUp() {
- userManager = UserManager.getInstance();
- setTitle("Sign Up");
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setResizable(false);
- setSize(320, 150);
- setLocationRelativeTo(null); // Center the window on the screen
- JPanel panel = new JPanel();
- panel.setLayout(new GridLayout(3, 2, 5, 5));
- JLabel usernameLabel = new JLabel("Username:");
- panel.add(usernameLabel);
- usernameField = new JTextField();
- panel.add(usernameField);
- JLabel passwordLabel = new JLabel("Password:");
- panel.add(passwordLabel);
- passwordField = new JPasswordField();
- panel.add(passwordField);
- JButton signUpButton = new JButton("Sign Up");
- signUpButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- signUp();
- }
- });
- panel.add(signUpButton);
- errorLabel = new JLabel("");
- errorLabel.setForeground(Color.RED);
- panel.add(errorLabel);
- add(panel);
- setVisible(true);
- }
- private void signUp() {
- String username = usernameField.getText();
- String password = new String(passwordField.getPassword());
- if (username.isEmpty() || password.isEmpty()) {
- errorLabel.setText("Username and password cannot be empty.");
- } else {
- if (userManager.addUser(username, password)) {
- dispose(); // Close the sign-up frame
- // Proceed to the login frame
- SwingUtilities.invokeLater(Login::new);
- } else {
- errorLabel.setText("Username already exists.");
- }
- }
- }
- }
- class AdminPane extends JFrame {
- private JTable bookTable;
- private DefaultTableModel bookTableModel;
- private BookManager bookManager; // Instantiate the BookManager
- public AdminPane() {
- setTitle("Admin Panel");
- setSize(800, 600);
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- getContentPane().setBackground(Color.LIGHT_GRAY);
- // Instantiate the BookManager
- bookManager = BookManager.getInstance();
- // Main panel with BorderLayout
- JPanel mainPanel = new JPanel();
- setContentPane(mainPanel);
- // Books table
- bookTableModel = new DefaultTableModel(new Object[] { "Title", "Author", "Quantity", "Price", "Genre" }, 0);
- mainPanel.setLayout(new BorderLayout());
- JPanel panel = new JPanel();
- panel.setBorder(new TitledBorder(
- new EtchedBorder(EtchedBorder.LOWERED, new Color(255, 255, 255), new Color(160, 160, 160)), "Books",
- TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
- mainPanel.add(panel, BorderLayout.CENTER);
- panel.setLayout(new BorderLayout(0, 0));
- bookTable = new JTable(bookTableModel);
- JScrollPane bookScrollPane = new JScrollPane(bookTable);
- bookScrollPane.setPreferredSize(new Dimension(100, 150));
- panel.add(bookScrollPane, BorderLayout.CENTER);
- JPanel buttonsPanel = new JPanel();
- panel.add(buttonsPanel, BorderLayout.SOUTH);
- JButton addBookBtn = new JButton("Add Book");
- addBookBtn.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- // Add book functionality
- addBook();
- }
- });
- buttonsPanel.add(addBookBtn);
- JButton updateBookBtn = new JButton("Update Book");
- updateBookBtn.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- // Update book functionality
- updateBook();
- }
- });
- buttonsPanel.add(updateBookBtn);
- JButton removeBookBtn = new JButton("Remove Book");
- removeBookBtn.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- // Remove book functionality
- removeBook();
- }
- });
- buttonsPanel.add(removeBookBtn);
- JButton logoutBtn = new JButton("Logout");
- logoutBtn.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- dispose();
- SwingUtilities.invokeLater(Login::new);
- }
- });
- buttonsPanel.add(logoutBtn);
- // Populate table with existing books
- refreshBookTable();
- setVisible(true);
- }
- private void refreshBookTable() {
- // Clear existing rows
- bookTableModel.setRowCount(0);
- // Get all books from the BookManager
- List<Book> allBooks = bookManager.getAllBooks();
- // Add each book to the table
- for (Book book : allBooks) {
- // Add book details including the genre
- bookTableModel.addRow(new Object[] { book.getTitle(), book.getAuthor(), book.getQuantity(), book.getPrice(),
- book.getGenre() });
- }
- }
- private void addBook() {
- // Prompt the admin for book details
- String title = JOptionPane.showInputDialog("Enter title:");
- String author = JOptionPane.showInputDialog("Enter author:");
- String quantityStr = JOptionPane.showInputDialog("Enter quantity:");
- String priceStr = JOptionPane.showInputDialog("Enter price:");
- String genre = JOptionPane.showInputDialog("Enter genre (Fiction or Non-Fiction):");
- // Convert quantity and price to integers
- int quantity = Integer.parseInt(quantityStr);
- double price = Double.parseDouble(priceStr);
- // Create a new Book object
- Book newBook = new Book(title, author, quantity, price, genre);
- // Add the new book to the BookManager
- bookManager.addBook(newBook);
- // Refresh the table
- refreshBookTable();
- }
- private void removeBook() {
- int selectedRow = bookTable.getSelectedRow();
- if (selectedRow != -1) {
- int confirm = JOptionPane.showConfirmDialog(null, "Are you sure you want to remove this book?",
- "Confirm Removal", JOptionPane.YES_NO_OPTION);
- if (confirm == JOptionPane.YES_OPTION) {
- bookManager.removeBook(selectedRow);
- refreshBookTable();
- }
- } else {
- JOptionPane.showMessageDialog(null, "Please select a book to remove.");
- }
- }
- private void updateBook() {
- int selectedRow = bookTable.getSelectedRow();
- if (selectedRow != -1) {
- Book selectedBook = bookManager.getAllBooks().get(selectedRow);
- // Prompt the admin for updated details
- String title = JOptionPane.showInputDialog("Enter updated title:", selectedBook.getTitle());
- String author = JOptionPane.showInputDialog("Enter updated author:", selectedBook.getAuthor());
- String quantityStr = JOptionPane.showInputDialog("Enter updated quantity:", selectedBook.getQuantity());
- String priceStr = JOptionPane.showInputDialog("Enter updated price:", selectedBook.getPrice());
- // Convert quantity and price to integers
- int quantity = Integer.parseInt(quantityStr);
- double price = Double.parseDouble(priceStr);
- // Prompt the admin for updated details including the genre
- String genre = JOptionPane.showInputDialog("Enter updated genre (Fiction or Non-Fiction):");
- // Create an updated Book object
- Book updatedBook = new Book(title, author, quantity, price, genre);
- // Update the book in the BookManager
- bookManager.updateBook(selectedRow, updatedBook);
- // Refresh the table
- refreshBookTable();
- } else {
- JOptionPane.showMessageDialog(null, "Please select a book to update.");
- }
- }
- }
- public class OnlineBookStore extends JFrame {
- private JTable bookTable, cartTable;
- private JComboBox<String> categoryComboBox;
- private DefaultTableModel bookTableModel, cartTableModel;
- private JLabel errorLabel;
- private List<Book> books = new ArrayList<>();
- private List<Book> cart = new ArrayList<>();
- private BookManager bookManager; // Add a reference to BookManager
- private List<Order> orders = new ArrayList<>();
- public OnlineBookStore() {
- setTitle("Online Bookstore Management System");
- setSize(800, 600);
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- getContentPane().setBackground(Color.LIGHT_GRAY);
- // Instantiate the BookManager
- bookManager = BookManager.getInstance();
- ;
- // Populate books list with existing books from BookManager
- books = bookManager.getAllBooks();
- // Initialize the bookTableModel
- bookTableModel = new DefaultTableModel(new Object[] { "Title", "Author", "Quantity", "Price" }, 0);
- // Refresh the table to display all books by default
- refreshBookTable("All");
- // Main panel with BorderLayout
- JPanel mainPanel = new JPanel();
- setContentPane(mainPanel);
- // Cart table
- cartTableModel = new DefaultTableModel(new Object[] { "Title", "Author", "Quantity", "Price", "Genre" }, 0);
- mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
- JPanel panel = new JPanel();
- panel.setBorder(new TitledBorder(
- new EtchedBorder(EtchedBorder.LOWERED, new Color(255, 255, 255), new Color(160, 160, 160)), "Books",
- TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
- mainPanel.add(panel);
- panel.setLayout(new BorderLayout(0, 0));
- // Category dropdown and search button
- JPanel booksPanel = new JPanel();
- panel.add(booksPanel, BorderLayout.NORTH);
- booksPanel.setLayout(new BorderLayout(0, 0));
- JPanel searchPanel = new JPanel();
- panel.add(searchPanel, BorderLayout.NORTH);
- JButton searchButton = new JButton("Search/Browse");
- searchButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- String selectedGenre = (String) categoryComboBox.getSelectedItem();
- refreshBookTable(selectedGenre);
- }
- });
- searchPanel.add(searchButton);
- categoryComboBox = new JComboBox<>(new String[] { "All", "Fiction", "Non-fiction" });
- searchPanel.add(categoryComboBox);
- bookTable = new JTable(bookTableModel);
- JScrollPane bookScrollPane = new JScrollPane(bookTable);
- panel.add(bookScrollPane, BorderLayout.CENTER);
- bookScrollPane.setBounds(10, 121, 311, 118);
- bookScrollPane.setPreferredSize(new Dimension(350, 200));
- JPanel buttonsAndErrorPanel = new JPanel();
- panel.add(buttonsAndErrorPanel, BorderLayout.SOUTH);
- buttonsAndErrorPanel.setLayout(new GridLayout(0, 2, 0, 0));
- errorLabel = new JLabel("");
- errorLabel.setHorizontalAlignment(SwingConstants.RIGHT);
- buttonsAndErrorPanel.add(errorLabel);
- JButton addToCartBtn = new JButton("Add To Cart");
- addToCartBtn.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- int selectedRow = bookTable.getSelectedRow();
- if (selectedRow != -1) {
- Book selectedBook = books.get(selectedRow);
- if (selectedBook.getQuantity() > 0) {
- addToCart(selectedBook);
- refreshCartTable();
- selectedBook.decreaseQuantity();
- refreshBookTable("All");
- } else {
- showError("Selected book is out of stock!");
- }
- } else {
- showError("Please select a book to add to cart!");
- }
- }
- });
- buttonsAndErrorPanel.add(addToCartBtn);
- // Login button
- JButton logout = new JButton("Logout");
- logout.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- dispose();
- SwingUtilities.invokeLater(Login::new);
- }
- });
- buttonsAndErrorPanel.add(logout);
- JPanel addToCartPanel = new JPanel();
- addToCartPanel.setBorder(new TitledBorder(
- new EtchedBorder(EtchedBorder.LOWERED, new Color(255, 255, 255), new Color(160, 160, 160)),
- "Add To Cart Panel", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
- mainPanel.add(addToCartPanel);
- addToCartPanel.setLayout(new BorderLayout(0, 0));
- JPanel btnPanel = new JPanel();
- addToCartPanel.add(btnPanel, BorderLayout.SOUTH);
- JButton updateQuantityBtn = new JButton("Update Cart");
- updateQuantityBtn.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- int selectedRow = cartTable.getSelectedRow();
- if (selectedRow != -1) {
- String input = JOptionPane.showInputDialog("Enter new quantity:");
- try {
- int newQuantity = Integer.parseInt(input);
- if (newQuantity > 0) {
- Book selectedBook = cart.get(selectedRow);
- selectedBook.setQuantity(newQuantity);
- refreshCartTable();
- } else {
- showError("Quantity must be a positive number!");
- }
- } catch (NumberFormatException ex) {
- showError("Invalid input! Please enter a number.");
- }
- } else {
- showError("Please select a book from the cart to update quantity.");
- }
- }
- });
- btnPanel.add(updateQuantityBtn);
- JButton removeFromCartBtn = new JButton("Remove");
- removeFromCartBtn.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- int selectedRow = cartTable.getSelectedRow();
- if (selectedRow != -1) {
- Book removedBook = cart.remove(selectedRow);
- for (Book book : books) {
- if (book.getTitle().equals(removedBook.getTitle())) {
- book.setQuantity(book.getQuantity() + removedBook.getQuantity());
- break;
- }
- }
- refreshCartTable();
- refreshBookTable("All");
- } else {
- showError("Please select a book from the cart to remove.");
- }
- }
- });
- btnPanel.add(removeFromCartBtn);
- JButton placeOrderBtn = new JButton("Place Order");
- placeOrderBtn.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- placeOrder();
- }
- });
- btnPanel.add(placeOrderBtn);
- cartTable = new JTable(cartTableModel);
- JScrollPane cartScrollPane = new JScrollPane(cartTable);
- addToCartPanel.add(cartScrollPane);
- cartScrollPane.setPreferredSize(new Dimension(350, 200));
- setVisible(true);
- refreshBookTable("All");
- }
- private void refreshBookTable(String genre) {
- bookTableModel.setRowCount(0);
- List<Book> filteredBooks = bookManager.getBooksByGenre(genre);
- for (Book book : filteredBooks) {
- bookTableModel
- .addRow(new Object[] { book.getTitle(), book.getAuthor(), book.getQuantity(), book.getPrice() });
- }
- }
- private void refreshCartTable() {
- cartTableModel.setRowCount(0);
- for (Book book : cart) {
- cartTableModel.addRow(new Object[] { book.getTitle(), book.getAuthor(), book.getQuantity(), book.getPrice(),
- book.getGenre() });
- }
- }
- private void addToCart(Book book) {
- cart.add(book);
- }
- private void showError(String message) {
- errorLabel.setText(message);
- }
- private void placeOrder() {
- if (cart.isEmpty()) {
- JOptionPane.showMessageDialog(null, "Your cart is empty. Please add items before placing an order.");
- } else {
- int confirm = JOptionPane.showConfirmDialog(null, "Are you sure you want to place this order?",
- "Confirm Order", JOptionPane.YES_NO_OPTION);
- if (confirm == JOptionPane.YES_OPTION) {
- double totalPrice = 0.0;
- for (Book book : cart) {
- totalPrice += book.getPrice() * book.getQuantity();
- }
- // Create and store the new order
- Order newOrder = new Order(cart, totalPrice);
- orders.add(newOrder);
- // Clear the cart
- cart.clear();
- refreshCartTable();
- refreshBookTable("All");
- // Display the list of orders using JOptionPane
- StringBuilder orderList = new StringBuilder();
- for (Order order : orders) {
- orderList.append(order.toString()).append("\n");
- }
- JOptionPane.showMessageDialog(this, orderList.toString(), "Orders to Ship",
- JOptionPane.INFORMATION_MESSAGE);
- }
- }
- }
- public static void main(String[] args) {
- SwingUtilities.invokeLater(SignUp::new);
- }
- }
- class Order {
- private List<Book> orderedBooks;
- private double totalPrice;
- public Order(List<Book> orderedBooks, double totalPrice) {
- this.orderedBooks = new ArrayList<>(orderedBooks);
- this.totalPrice = totalPrice;
- }
- public List<Book> getOrderedBooks() {
- return orderedBooks;
- }
- public double getTotalPrice() {
- return totalPrice;
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("Order Details:\n");
- for (Book book : orderedBooks) {
- sb.append(" - ").append(book.getTitle()).append(" by ").append(book.getAuthor()).append(", Quantity: ")
- .append(book.getQuantity()).append(", Price: $").append(book.getPrice()).append("\n");
- }
- sb.append("Total Price: $").append(totalPrice).append("\n");
- return sb.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement