79832213

Date: 2025-11-28 03:00:31
Score: 0.5
Natty:
Report link
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class BurgerSystem extends JFrame {

    private CardLayout card;
    private JPanel mainPanel;

    private static class Account {
        String username, password;
        boolean isAdmin;
        Account(String u, String p, boolean admin) {
            this.username = u; this.password = p; this.isAdmin = admin;
        }
    }

    private static class LoginLog {
        String username, role, timestamp;
        LoginLog(String u, String r) {
            this.username = u; this.role = r;
            this.timestamp = new SimpleDateFormat("MMM dd, yyyy - hh:mm:ss a").format(new Date());
        }
    }

    private Map<String, Account> accounts = new HashMap<>();
    private List<LoginLog> loginLogs = new ArrayList<>();
    private Account currentUser = null;

    private JLabel lblWelcome = new JLabel();
    private JLabel lblItemPrice = new JLabel("0.00");
    private JLabel lblTotalAmount = new JLabel("0.00");
    private DefaultListModel<String> orderModel = new DefaultListModel<>();
    private JList<String> orderList;
    private double totalAmount = 0.0;

    private Map<String, Double> burgerPrices = new HashMap<>();
    private List<String> currentOrderItems = new ArrayList<>();

    // Use a mutable HashSet for compatibility
    private final Set<String> bogoItems = new HashSet<>(Arrays.asList("Sulit Burger", "Chicken Burger", "Cheeseburger"));

    public BurgerSystem() {
        setTitle("Sweet Angels Burger - POS System");
        setSize(1000, 700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);

        orderList = new JList<>(orderModel);
        orderList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        initBurgerPrices();
        initDefaultAdmin();

        card = new CardLayout();
        mainPanel = new JPanel(card);

        mainPanel.add(createLoginPanel(), "login");
        mainPanel.add(createRegisterPanel(), "register");
        mainPanel.add(createAdminPanel(), "admin");
        mainPanel.add(createCustomerPanel(), "customer");

        add(mainPanel);
        card.show(mainPanel, "login");
        setVisible(true);
    }

    private void initDefaultAdmin() {
        accounts.put("admin", new Account("admin", "admin123", true));
    }

    private void initBurgerPrices() {
        burgerPrices.put("Sulit Burger", 39.0);
        burgerPrices.put("Chicken Burger", 49.0);
        burgerPrices.put("Cheeseburger", 49.0);
        burgerPrices.put("Breakfast Burger", 59.0);
        burgerPrices.put("Ultimate Burger", 59.0);
        burgerPrices.put("Cheesy Hotdog", 49.0);
        burgerPrices.put("Chick 'n Hotdog", 49.0);
    }

    private JPanel createLoginPanel() {
        JPanel p = new JPanel(null);
        p.setBackground(new Color(255, 230, 102));

        JLabel title = new JLabel("SWEET ANGELS BURGER", SwingConstants.CENTER);
        title.setBounds(0, 80, 1000, 70);
        title.setFont(new Font("Arial Black", Font.BOLD, 48));
        title.setForeground(new Color(178, 34, 34));
        p.add(title);

        JTextField tfUser = new JTextField();
        tfUser.setBounds(350, 230, 300, 50);
        tfUser.setBorder(BorderFactory.createTitledBorder("Username"));
        p.add(tfUser);

        JPasswordField tfPass = new JPasswordField();
        tfPass.setBounds(350, 290, 300, 50);
        tfPass.setBorder(BorderFactory.createTitledBorder("Password"));
        p.add(tfPass);

        JCheckBox show = new JCheckBox("Show Password");
        show.setBounds(350, 345, 150, 30);
        show.setBackground(new Color(255, 230, 102));
        show.addActionListener(e -> tfPass.setEchoChar(show.isSelected() ? (char)0 : '•'));
        p.add(show);

        JButton login = new JButton("LOGIN");
        login.setBounds(350, 400, 300, 60);
        login.setBackground(new Color(255, 140, 0));
        login.setForeground(Color.WHITE);
        login.setFont(new Font("Arial", Font.BOLD, 24));
        login.addActionListener(e -> loginUser(tfUser.getText().trim(), new String(tfPass.getPassword())));
        p.add(login);

        JButton reg = new JButton("Register as Customer");
        reg.setBounds(350, 480, 300, 40);
        reg.addActionListener(e -> card.show(mainPanel, "register"));
        p.add(reg);

        return p;
    }

    private void loginUser(String user, String pass) {
        Account acc = accounts.get(user);
        if (acc != null && acc.password.equals(pass)) {
            currentUser = acc;
            loginLogs.add(0, new LoginLog(user, acc.isAdmin ? "Admin" : "Customer"));
            lblWelcome.setText("Welcome, " + user + (acc.isAdmin ? " (Admin)" : ""));
            clearOrder();
            card.show(mainPanel, acc.isAdmin ? "admin" : "customer");
        } else {
            JOptionPane.showMessageDialog(this, "Invalid username or password!", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private JPanel createRegisterPanel() {
        JPanel p = new JPanel(null);
        p.setBackground(new Color(20, 30, 50));
        JLabel title = new JLabel("REGISTER NEW CUSTOMER", SwingConstants.CENTER);
        title.setBounds(0, 100, 1000, 60);
        title.setFont(new Font("Arial", Font.BOLD, 36));
        title.setForeground(Color.WHITE);
        p.add(title);

        JTextField tfUser = new JTextField();
        tfUser.setBounds(350, 220, 300, 50);
        tfUser.setBorder(BorderFactory.createTitledBorder("Username"));
        p.add(tfUser);

        JPasswordField tfPass = new JPasswordField();
        tfPass.setBounds(350, 290, 300, 50);
        tfPass.setBorder(BorderFactory.createTitledBorder("Password"));
        p.add(tfPass);

        JButton reg = new JButton("CREATE ACCOUNT");
        reg.setBounds(350, 360, 300, 60);
        reg.setBackground(Color.GREEN.darker());
        reg.setForeground(Color.WHITE);
        reg.setFont(new Font("Arial", Font.BOLD, 20));
        reg.addActionListener(e -> {
            String u = tfUser.getText().trim();
            String p = new String(tfPass.getPassword());
            if (u.isEmpty() || p.isEmpty()) {
                JOptionPane.showMessageDialog(this, "Fill all fields!");
                return;
            }
            if (accounts.containsKey(u)) {
                JOptionPane.showMessageDialog(this, "Username already exists!");
                return;
            }
            accounts.put(u, new Account(u, p, false));
            JOptionPane.showMessageDialog(this, "Registered: " + u);
            card.show(mainPanel, "login");
        });
        p.add(reg);

        JButton back = new JButton("Back to Login");
        back.setBounds(350, 440, 300, 40);
        back.addActionListener(e -> card.show(mainPanel, "login"));
        p.add(back);

        return p;
    }

    private JPanel createCustomerPanel() {
        JPanel p = new JPanel(null);
        p.setBackground(new Color(255, 255, 179));

        JLabel title = new JLabel("SWEET ANGELS BURGER - BUY 1 TAKE 1!", SwingConstants.CENTER);
        title.setBounds(0, 30, 1000, 60);
        title.setFont(new Font("Arial Black", Font.BOLD, 36));
        title.setForeground(new Color(178, 34, 34));
        p.add(title);

        lblWelcome.setBounds(30, 100, 600, 40);
        lblWelcome.setFont(new Font("Arial", Font.BOLD, 22));
        lblWelcome.setForeground(new Color(0, 0, 139));
        p.add(lblWelcome);

        JButton logout = new JButton("Logout");
        logout.setBounds(860, 100, 100, 40);
        logout.addActionListener(e -> logout());
        p.add(logout);

        JPanel menu = createBurgerGrid();
        menu.setBounds(30, 150, 460, 500);
        p.add(menu);

        JPanel order = createOrderPanel(false);
        order.setBounds(510, 150, 460, 500);
        p.add(order);

        return p;
    }

    private JPanel createBurgerGrid() {
        JPanel wrapper = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 20));
        wrapper.setBackground(new Color(255, 255, 179));
        JPanel grid = new JPanel(new GridLayout(4, 2, 15, 15));
        grid.setBackground(new Color(255, 255, 179));

        String[][] items = {
            {"Sulit Burger", "BOGO PHP 39"},
            {"Chicken Burger", "BOGO PHP 49"},
            {"Cheeseburger", "BOGO PHP 49"},
            {"Breakfast Burger", "PHP 59"},
            {"Ultimate Burger", "PHP 59"},
            {"Cheesy Hotdog", "PHP 49"},
            {"Chick 'n Hotdog", "PHP 49"}
        };

        for (String[] item : items) {
            JButton btn = new JButton("<html><center><b>" + item[0] + "</b><br><font color='red' size='5'>" + item[1] + "</font></center></html>");
            btn.setPreferredSize(new Dimension(200, 100));
            btn.setBackground(new Color(255, 200, 0));
            btn.setFont(new Font("Arial", Font.BOLD, 15));
            btn.addActionListener(e -> addBurgerToOrder(item[0]));
            grid.add(btn);
        }
        wrapper.add(grid);
        return wrapper;
    }

    private void addBurgerToOrder(String name) {
        currentOrderItems.add(name);
        double price = burgerPrices.getOrDefault(name, 0.0);
        String bogo = bogoItems.contains(name) ? " (BOGO)" : "";
        orderModel.addElement("• " + name + bogo + " @ PHP " + String.format("%.2f", price));
        lblItemPrice.setText(String.format("%.2f", price));
        recalculateTotal();
    }

    private void removeSelectedItem() {
        int idx = orderList.getSelectedIndex();
        if (idx == -1) {
            JOptionPane.showMessageDialog(this, "Please select an item to remove!", "No Selection", JOptionPane.WARNING_MESSAGE);
            return;
        }
        String displayText = orderModel.getElementAt(idx);
        // safer parse: find the marker " @"
        int atPos = displayText.indexOf(" @");
        String itemNamePart = (atPos >= 0) ? displayText.substring(2, atPos) : displayText.substring(2);
        itemNamePart = itemNamePart.replace(" (BOGO)", "").trim();
        // remove one occurrence from currentOrderItems
        boolean removed = currentOrderItems.remove(itemNamePart);
        if (!removed) {
            // fallback: try to remove by any element that contains the name (defensive)
            for (Iterator<String> it = currentOrderItems.iterator(); it.hasNext();) {
                String itName = it.next();
                if (itName.equals(itemNamePart)) {
                    it.remove();
                    removed = true;
                    break;
                }
            }
        }
        orderModel.remove(idx);
        recalculateTotal();
        lblItemPrice.setText("0.00");
        JOptionPane.showMessageDialog(this, itemNamePart + " removed!", "Success", JOptionPane.INFORMATION_MESSAGE);
    }

    private void recalculateTotal() {
        totalAmount = 0.0;

        List<Double> bogoPrices = new ArrayList<>();
        double regularTotal = 0.0;

        for (String item : currentOrderItems) {
            double price = burgerPrices.getOrDefault(item, 0.0);
            if (bogoItems.contains(item)) {
                bogoPrices.add(price);
            } else {
                regularTotal += price;
            }
        }

        // Sort BOGO prices descending so customer pays for the more expensive ones in pairs
        bogoPrices.sort(Comparator.reverseOrder());

        for (int i = 0; i < bogoPrices.size(); i++) {
            if (i % 2 == 0) { // pay for 0,2,4...; 1,3,5 are free
                totalAmount += bogoPrices.get(i);
            }
        }

        totalAmount += regularTotal;
        lblTotalAmount.setText(String.format("%.2f", totalAmount));
    }

    private void clearOrder() {
        orderModel.clear();
        currentOrderItems.clear();
        totalAmount = 0.0;
        lblItemPrice.setText("0.00");
        lblTotalAmount.setText("0.00");
    }

    private JPanel createOrderPanel(boolean isAdmin) {
        JPanel p = new JPanel(null);
        p.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createLineBorder(Color.BLACK, 2),
            isAdmin ? "ADMIN POS TERMINAL" : "YOUR ORDER",
            TitledBorder.CENTER, TitledBorder.TOP,
            new Font("Arial", Font.BOLD, 16)
        ));
        p.setBackground(new Color(255, 255, 204));

        JScrollPane scroll = new JScrollPane(orderList);
        scroll.setBounds(20, 40, 300, 300);
        p.add(scroll);

        JLabel totalLbl = new JLabel("TOTAL: PHP");
        totalLbl.setBounds(20, 360, 120, 40);
        totalLbl.setFont(new Font("Arial", Font.BOLD, 20));
        p.add(totalLbl);

        lblTotalAmount.setBounds(140, 350, 280, 70);
        lblTotalAmount.setFont(new Font("Arial", Font.BOLD, 42));
        lblTotalAmount.setForeground(Color.RED);
        lblTotalAmount.setHorizontalAlignment(SwingConstants.RIGHT);
        lblTotalAmount.setOpaque(true);
        lblTotalAmount.setBackground(Color.YELLOW);
        p.add(lblTotalAmount);

        JButton removeBtn = new JButton("REMOVE SELECTED");
        removeBtn.setBounds(20, 440, 400, 60);
        removeBtn.setBackground(Color.RED.darker());
        removeBtn.setForeground(Color.WHITE);
        removeBtn.setFont(new Font("Arial", Font.BOLD, 20));
        removeBtn.addActionListener(e -> removeSelectedItem());
        p.add(removeBtn);

        JButton actionBtn = new JButton(isAdmin ? "PROCESS PAYMENT" : "PLACE ORDER");
        actionBtn.setBounds(20, 520, 400, 80);
        actionBtn.setBackground(Color.GREEN.darker().darker());
        actionBtn.setForeground(Color.WHITE);
        actionBtn.setFont(new Font("Arial", Font.BOLD, 26));
        actionBtn.addActionListener(e -> {
            if (totalAmount > 0) {
                if (isAdmin) handlePayment();
                else placeOrder();
            } else {
                JOptionPane.showMessageDialog(this, "Order is empty!");
            }
        });
        p.add(actionBtn);

        return p;
    }

    private void handlePayment() {
        String cashInput = JOptionPane.showInputDialog(this, "Enter Cash Amount (PHP):");
        if (cashInput != null && !cashInput.trim().isEmpty()) {
            try {
                double cash = Double.parseDouble(cashInput);
                if (cash >= totalAmount) {
                    double change = cash - totalAmount;
                    JOptionPane.showMessageDialog(this,
                        "PAYMENT SUCCESSFUL!\n\n" +
                        "Total: PHP " + String.format("%.2f", totalAmount) + "\n" +
                        "Cash: PHP " + String.format("%.2f", cash) + "\n" +
                        "Change: PHP " + String.format("%.2f", change),
                        "Thank You!", JOptionPane.INFORMATION_MESSAGE);
                    clearOrder();
                } else {
                    JOptionPane.showMessageDialog(this, "Not enough cash!");
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Invalid amount!");
            }
        }
    }

    private void placeOrder() {
        JOptionPane.showMessageDialog(this,
            "ORDER PLACED!\nTotal: PHP " + String.format("%.2f", totalAmount) + "\n\nThank you po!",
            "Success", JOptionPane.INFORMATION_MESSAGE);
        clearOrder();
    }

    private void logout() {
        if (JOptionPane.showConfirmDialog(this, "Logout?", "Confirm", JOptionPane.YES_NO_OPTION) == 0) {
            currentUser = null;
            clearOrder();
            card.show(mainPanel, "login");
        }
    }

    private JPanel createAdminPanel() {
        JPanel p = new JPanel(null);
        p.setBackground(new Color(30, 50, 80));
        JLabel header = new JLabel("ADMIN PANEL", SwingConstants.CENTER);
        header.setBounds(0, 10, 1000, 60);
        header.setFont(new Font("Arial", Font.BOLD, 36));
        header.setForeground(Color.YELLOW);
        header.setOpaque(true);
        header.setBackground(new Color(0, 100, 150));
        p.add(header);

        lblWelcome.setBounds(20, 80, 600, 40);
        lblWelcome.setFont(new Font("Arial", Font.BOLD, 20));
        lblWelcome.setForeground(Color.WHITE);
        p.add(lblWelcome);

        JButton logout = new JButton("Logout");
        logout.setBounds(860, 80, 100, 40);
        logout.addActionListener(e -> logout());
        p.add(logout);

        JTabbedPane tabs = new JTabbedPane();
        tabs.setBounds(20, 130, 960, 520);
        tabs.addTab("POS Terminal", createOrderPanel(true));
        tabs.addTab("Manage Accounts", new JPanel());
        tabs.addTab("Login History", new JPanel());
        p.add(tabs);
        return p;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(BurgerSystem::new);
    }
}
fix this code without error
Reasons:
  • Blacklisted phrase (0.5): Thank You
  • Blacklisted phrase (0.5): Thank you
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: ryan ata