Untitled
unknown
plain_text
5 months ago
23 kB
4
Indexable
import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import java.awt.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; class Main { private User currentUser; // Currently logged-in user private SportsComplex complex; // Instance of SportsComplex public Main(User user, SportsComplex complex) { this.currentUser = user; // Assign the current user this.complex = complex; // Assign the SportsComplex instance createAndShowGUI(); // Create and display the main page } private void createAndShowGUI() { // Set up the main frame JFrame frame = new JFrame("Main Page"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 400); frame.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(5, 10, 5, 10); // Padding around components // Set background color of the frame to white frame.getContentPane().setBackground(Color.WHITE); // Add Welcome Label JLabel welcomeLabel = new JLabel("Hi! " + currentUser.getUsername() + ", Welcome to PlaySafe"); welcomeLabel.setFont(new Font("Arial", Font.BOLD, 20)); welcomeLabel.setForeground(Color.BLACK); // Set the welcome text to black gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; // Span across both columns frame.add(welcomeLabel, gbc); // Create buttons for various actions JButton checkAvailabilityButton = createStyledButton("Check Facility Availability", Color.BLACK); JButton viewPricingButton = createStyledButton("View Facility Pricing", Color.BLACK); JButton createBookingButton = createStyledButton("Create a Booking", Color.BLACK); JButton cancelBookingButton = createStyledButton("Cancel a Booking", Color.BLACK); JButton trackHistoryButton = createStyledButton("Track Booking History", Color.BLACK); JButton logoutButton = createStyledButton("Logout", Color.BLACK); // Add buttons to the frame - Group 1 gbc.gridwidth = 1; gbc.gridx = 0; gbc.gridy = 1; frame.add(checkAvailabilityButton, gbc); gbc.gridx = 0; gbc.gridy = 2; frame.add(viewPricingButton, gbc); // Add buttons to the frame - Group 2 gbc.gridx = 1; gbc.gridy = 1; frame.add(createBookingButton, gbc); gbc.gridx = 1; gbc.gridy = 2; frame.add(cancelBookingButton, gbc); // Add remaining buttons to the frame gbc.gridx = 0; gbc.gridy = 3; frame.add(trackHistoryButton, gbc); gbc.gridx = 1; gbc.gridy = 3; frame.add(logoutButton, gbc); // Set action listeners for buttons checkAvailabilityButton.addActionListener(e -> viewSchedule()); viewPricingButton.addActionListener(e -> viewFacilityPricing()); createBookingButton.addActionListener(e -> createBooking()); cancelBookingButton.addActionListener(e -> cancelBooking()); trackHistoryButton.addActionListener(e -> trackBookingHistory()); logoutButton.addActionListener(e -> { JOptionPane.showMessageDialog(null, "Thank you for using PlaySafe App!"); frame.dispose(); // Close the current frame new LoginForm(); // Return to login form }); // Make the frame visible frame.setVisible(true); } // Create a styled button with custom colors private JButton createStyledButton(String text, Color textColor) { JButton button = new JButton(text); button.setPreferredSize(new Dimension(200, 30)); button.setBackground(Color.WHITE); // Set button background to white button.setForeground(textColor); // Set button text color button.setFocusPainted(false); button.setFont(new Font("Arial", Font.BOLD, 12)); return button; } private Map<String, Boolean> facilityAvailability = new HashMap<>(); // To track facility availability private void initializeFacilityAvailability() { facilityAvailability.put("Basketball Court", true); facilityAvailability.put("Swimming Pool", true); facilityAvailability.put("Football Field", true); } private String[] facilities = {"Basketball Court", "Swimming Pool", "Football Field", "Volleyball Court", "Badminton Court"}; private int[] bookingCounts = new int[facilities.length]; private void viewSchedule() { JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(10, 10, 10, 10); gbc.anchor = GridBagConstraints.CENTER; // Title: View Schedule gbc.gridx = 0; // Column gbc.gridy = 0; // Row gbc.gridwidth = 2; JLabel titleLabel = new JLabel("View Schedule"); titleLabel.setFont(new Font("Arial", Font.BOLD, 20)); panel.add(titleLabel, gbc); gbc.gridy++; // Move to the next row gbc.gridwidth = 2; // Span across the whole row panel.add(new JSeparator(SwingConstants.HORIZONTAL), gbc); // Line separator JTextPane textPane = new JTextPane(); textPane.setEditable(false); // Make it non-editable textPane.setPreferredSize(new Dimension(400, 200)); // Set preferred size textPane.setBackground(new Color(240, 248, 255)); // Light background for readability textPane.setFont(new Font("Arial", Font.PLAIN, 15)); // Build the facility schedule content using StyledDocument for JTextPane StyledDocument doc = textPane.getStyledDocument(); SimpleAttributeSet centerAlign = new SimpleAttributeSet(); StyleConstants.setAlignment(centerAlign, StyleConstants.ALIGN_CENTER); doc.setParagraphAttributes(0, doc.getLength(), centerAlign, false); // Apply to the whole document // Set up date formatter for 12-hour format with AM/PM SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a"); // 12-hour format with AM/PM // Check if the user has any reservations List<Reservation> reservations = currentUser.getReservations(); // Assume currentUser is the logged-in user if (reservations.isEmpty()) { try { doc.insertString(doc.getLength(), "No reservations found.\n", null); } catch (BadLocationException e) { e.printStackTrace(); } } else { for (Reservation reservation : reservations) { try { String reservationInfo; // Format start and end times String formattedStartTime = timeFormat.format(parseTime(reservation.getTime())); String formattedEndTime = timeFormat.format(parseTime(reservation.getEndTime())); if (reservation.isCancelled()) { // Indicate that this reservation is canceled reservationInfo = String.format( "%s:\nID: %d, Event: %s, Date: %s, Time: %s - Ends at: %s [CANCELLED]\n", reservation.getFacilityName(), reservation.getId(), reservation.getEventName(), reservation.getDate(), formattedStartTime, formattedEndTime ); } else { // Display active reservations reservationInfo = String.format( "%s:\nID: %d, Event: %s, Date: %s, Time: %s - Ends at: %s\n", reservation.getFacilityName(), reservation.getId(), reservation.getEventName(), reservation.getDate(), formattedStartTime, formattedEndTime ); } // Insert the reservation info into the text pane doc.insertString(doc.getLength(), reservationInfo, null); } catch (BadLocationException e) { e.printStackTrace(); } } } JScrollPane scrollPane = new JScrollPane(textPane); scrollPane.setPreferredSize(new Dimension(400, 200)); gbc.gridy++; gbc.gridwidth = 2; panel.add(scrollPane, gbc); JOptionPane optionPane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION); JDialog dialog = optionPane.createDialog("View Schedule"); dialog.setSize(500, 400); dialog.setVisible(true); } // Helper method to parse time strings (in "HH:mm" format) to Date objects private Date parseTime(String time) { SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm"); // 24-hour format try { return timeFormat.parse(time); // Parse the time string to a Date object } catch (Exception e) { e.printStackTrace(); return null; } } private void viewFacilityPricing() { // Create a panel with GridBagLayout for flexible layout JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(10, 10, 10, 10); // Padding around components gbc.anchor = GridBagConstraints.CENTER; // Center-align components // Title: Facility Pricing (centered) gbc.gridx = 0; // Column gbc.gridy = 0; // Row gbc.gridwidth = 2; // Span across two columns for centering JLabel titleLabel = new JLabel("Facility Price List"); titleLabel.setFont(new Font("Arial", Font.BOLD, 20)); // Larger, bold font for title panel.add(titleLabel, gbc); // Add a divider or line break gbc.gridy++; // Move to the next row gbc.gridwidth = 2; // Span across the whole row panel.add(new JSeparator(SwingConstants.HORIZONTAL), gbc); // Line separator // Create JTextPane to display facility pricing JTextPane textPane = new JTextPane(); textPane.setEditable(false); // Make it non-editable textPane.setPreferredSize(new Dimension(400, 200)); // Set preferred size textPane.setBackground(new Color(240, 248, 255)); // Light background for readability textPane.setFont(new Font("Arial", Font.PLAIN, 14)); // Set the font to Arial // Get the styled document to add styles to the JTextPane StyledDocument doc = textPane.getStyledDocument(); // Center alignment for the text SimpleAttributeSet centered = new SimpleAttributeSet(); StyleConstants.setAlignment(centered, StyleConstants.ALIGN_CENTER); // Add each facility and its price try { doc.setParagraphAttributes(0, doc.getLength(), centered, false); for (Facility facility : complex.facilities.values()) { doc.insertString(doc.getLength(), facility.getName() + ": ₱" + facility.getPricePerHour() + " per hour\n", null); } } catch (BadLocationException e) { e.printStackTrace(); } // Add the JTextPane wrapped in a JScrollPane to handle overflow JScrollPane scrollPane = new JScrollPane(textPane); scrollPane.setPreferredSize(new Dimension(400, 200)); // Set preferred size gbc.gridy++; // Move to the next row for JTextPane gbc.gridwidth = 2; // Span across the whole row panel.add(scrollPane, gbc); // Add JTextPane to the panel // Show the facility pricing in a dialog JOptionPane optionPane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION); JDialog dialog = optionPane.createDialog("Facility Pricing"); dialog.setSize(500, 400); dialog.setVisible(true); // Show the dialog } private void createBooking() { // Define available facilities String[] facilities = {"Basketball Court", "Swimming Pool", "Football Field", "Volleyball Court", "Badminton Court"}; // Add more facilities as needed // Create a combo box for facility selection JComboBox<String> facilityComboBox = new JComboBox<>(facilities); facilityComboBox.setSelectedIndex(0); // Set default selection // Create input fields for other booking details JTextField eventNameField = new JTextField(20); // Create input fields for date JTextField dateField = new JTextField(10); dateField.setText(new java.text.SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())); // Set current date as default // Create input field for time JTextField timeField = new JTextField(5); timeField.setText(new java.text.SimpleDateFormat("hh:mm").format(Calendar.getInstance().getTime())); // Set current time as default // Create a combo box for AM/PM selection String[] amPmOptions = {"AM", "PM"}; JComboBox<String> amPmComboBox = new JComboBox<>(amPmOptions); amPmComboBox.setSelectedItem("AM"); // Set default to AM // Create input field for duration JTextField durationField = new JTextField(5); // Create a panel to hold the input components JPanel panel = new JPanel(new GridLayout(0, 1)); // Vertical layout panel.add(new JLabel("Select Facility:")); panel.add(facilityComboBox); panel.add(new JLabel("Enter Event:")); panel.add(eventNameField); panel.add(new JLabel("Enter Date (YYYY-MM-DD):")); panel.add(dateField); panel.add(new JLabel("Enter Time (hh:mm):")); panel.add(timeField); panel.add(amPmComboBox); // Add AM/PM selection panel.add(new JLabel("Enter Duration in Hours:")); panel.add(durationField); // Show the input dialog int result = JOptionPane.showConfirmDialog(null, panel, "Create Booking", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); // If user clicked OK, proceed with booking if (result == JOptionPane.OK_OPTION) { String facilityName = (String) facilityComboBox.getSelectedItem(); String eventName = eventNameField.getText(); String date = dateField.getText(); String time = timeField.getText() + " " + amPmComboBox.getSelectedItem(); // Combine time and AM/PM int duration; // Validate and parse duration try { duration = Integer.parseInt(durationField.getText()); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid duration. Please enter a number.", "Error", JOptionPane.ERROR_MESSAGE); return; // Exit the method if duration is invalid } // Validate date format (basic check) if (!date.matches("\\d{4}-\\d{2}-\\d{2}")) { JOptionPane.showMessageDialog(null, "Invalid date format. Please use YYYY-MM-DD.", "Error", JOptionPane.ERROR_MESSAGE); return; } // Validate time format (basic check) if (!time.matches("\\d{1,2}:\\d{2} (AM|PM)")) { JOptionPane.showMessageDialog(null, "Invalid time format. Please use hh:mm AM/PM.", "Error", JOptionPane.ERROR_MESSAGE); return; } // Attempt to make a reservation and show the result String message = complex.makeReservation(currentUser, facilityName, eventName, date, time, duration); JOptionPane.showMessageDialog(null, message); } } private void cancelBooking() { // Create a panel to hold the input components with more spacing JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(10, 10, 10, 10); // Add padding around components // Add a label for the reservation ID gbc.gridx = 0; // Column gbc.gridy = 0; // Row gbc.anchor = GridBagConstraints.CENTER; // Center alignment panel.add(new JLabel("Enter Reservation ID to Cancel:"), gbc); // Input field for reservation ID JTextField reservationIdField = new JTextField(15); // Wider field reservationIdField.setPreferredSize(new Dimension(200, 30)); // Set preferred size gbc.gridx = 0; // Column gbc.gridy = 1; // Row panel.add(reservationIdField, gbc); // Calculate dialog size based on the preferred sizes Dimension size = new Dimension(300, 150); // Default size panel.setPreferredSize(size); // Show the input dialog with a custom size JOptionPane optionPane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); JDialog dialog = optionPane.createDialog("Cancel Booking"); // Set the dialog size to accommodate the panel dialog.pack(); // Automatically sizes the dialog to fit the components dialog.setLocationRelativeTo(null); // Center the dialog on the screen dialog.setVisible(true); // Show the dialog // Get the user’s choice Object selectedValue = optionPane.getValue(); if (selectedValue == null) { return; // User closed the dialog without action } // If user clicked OK, proceed with cancellation if (selectedValue.equals(JOptionPane.OK_OPTION)) { String reservationIdText = reservationIdField.getText(); int reservationId; // Validate and parse reservation ID try { reservationId = Integer.parseInt(reservationIdText); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid ID. Please enter a numeric reservation ID.", "Error", JOptionPane.ERROR_MESSAGE); return; // Exit the method if the ID is invalid } // Confirmation dialog int confirmation = JOptionPane.showConfirmDialog(null, "Are you sure you want to cancel reservation ID: " + reservationId + "?", "Confirm Cancellation", JOptionPane.YES_NO_OPTION); // If user confirms, attempt to cancel the reservation and show the result if (confirmation == JOptionPane.YES_OPTION) { if (complex.cancelReservation(currentUser, reservationId)) { JOptionPane.showMessageDialog(null, "Reservation canceled successfully.", "Success", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Reservation ID not found. Please check and try again.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "Cancellation aborted.", "Info", JOptionPane.INFORMATION_MESSAGE); } } } private void trackBookingHistory() { List<Reservation> reservations = currentUser.getReservations(); // Assume this method exists // Create the panel to hold the UI components JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(10, 10, 10, 10); gbc.anchor = GridBagConstraints.CENTER; // Title: Booking History gbc.gridx = 0; // Column gbc.gridy = 0; // Row gbc.gridwidth = 2; JLabel titleLabel = new JLabel("Reservations History"); titleLabel.setFont(new Font("Arial", Font.BOLD, 20)); panel.add(titleLabel, gbc); gbc.gridy++; // Move to the next row gbc.gridwidth = 2; // Span across the whole row panel.add(new JSeparator(SwingConstants.HORIZONTAL), gbc); // Line separator JTextPane textPane = new JTextPane(); textPane.setEditable(false); // Make it non-editable textPane.setPreferredSize(new Dimension(400, 200)); // Set preferred size textPane.setBackground(new Color(240, 248, 255)); textPane.setFont(new Font("Arial", Font.PLAIN, 14)); StyledDocument doc = textPane.getStyledDocument(); // Center alignment for the text SimpleAttributeSet centered = new SimpleAttributeSet(); StyleConstants.setAlignment(centered, StyleConstants.ALIGN_CENTER); // Add a date formatter for 12-hour time with AM/PM SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a"); // Add each reservation to the JTextPane try { doc.setParagraphAttributes(0, doc.getLength(), centered, false); if (reservations.isEmpty()) { doc.insertString(doc.getLength(), "No reservations history found.\n", null); } else { for (Reservation reservation : reservations) { // Format the start and end times String formattedStartTime = timeFormat.format(parseTime(reservation.getTime())); String formattedEndTime = timeFormat.format(parseTime(reservation.getEndTime())); // Add reservation information doc.insertString(doc.getLength(), String.format("Facility: %s, Date: %s, Time: %s - Ends at: %s\nReserved by: %s\n\n", reservation.getFacilityName(), reservation.getDate(), formattedStartTime, formattedEndTime, reservation.getReservedBy()), // Assuming you have this field in the Reservation class null); } } } catch (BadLocationException e) { e.printStackTrace(); } JScrollPane scrollPane = new JScrollPane(textPane); scrollPane.setPreferredSize(new Dimension(400, 200)); // Set preferred size gbc.gridy++; // Move to the next row for JTextPane gbc.gridwidth = 2; // Span across the whole row panel.add(scrollPane, gbc); // Add JTextPane to the panel // Create the JOptionPane dialog JOptionPane optionPane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION); JDialog dialog = optionPane.createDialog("Your Reservations History"); dialog.setSize(500, 400); dialog.setVisible(true); } }
Editor is loading...
Leave a Comment