Question: Need the code for this along with skeleton. PLEASE HELP! The necessary code for TicketMaster and TrainTravelGUI is given at the end! Train Travel Design
Need the code for this along with skeleton. PLEASE HELP! The necessary code for TicketMaster and TrainTravelGUI is given at the end!
Train Travel
Design
We provide here the complete design that you must implement. Your program must consist of twelve different classes and one interface inside four different packages. We are providing the interface and the graphical user interface front end.
train_travel.manager
TicketMaster. An interface that describes behaviors required to manage train reservations. You cannot change this code in any way. ReservationManager must implement TicketMaster.
ReservationManager. Concrete class for managing (adding, removing, changing) train reservations. ReservationManager keeps track of reservations in an ArrayList of Reservations.
train_travel.tickets
Reservation. Abstract class representing a reservation for train travel. Reservation has a Train named myTrain.
ComfortClass. Concrete class derived from Reservation and representing a Comfort Class reservation.
EconomyClass. Concrete class derived from Reservation and representing an Economy Class reservation.
BicycleClass. Concrete class derived from Reservation and representing a reservation for passengers with bicycles.
train_travel.transportation
Seat. Concrete class representing a seat on a train.
TrainCar. Abstract class representing a car on a train.
FirstClassCar. Concrete class derived from TrainCar and representing a First Class train car. FirstClassCar has a two-dimensional array of Seats.
SecondClassCar. Concrete class derived from TrainCar and representing a Second Class train car. SecondClassCar has a two-dimensional array of Seats.
BicycleTransportCar. Concrete class derived from TrainCar and representing train car for Bicycle Transport.
Train. Concrete class that represents a train. Train has an array of TrainCars.
train_travel.ui
TrainTravelGUI. A graphical user interface for the system. TrainTravelGUI is connected to the back end model through its TicketMaster, which is implemented as a ReservationManager. TrainTravelGUI is the class that starts execution of the program. You should not change this code in any way
UML diagram notations
UML uses standard conventions for display of data, methods, and relationships. Many are illustrated in the UML diagram above. Here are some things you should note:
- in front of a class member means private.
+ in front of a class member means public.
# in front of a class member means protected.
Static members (data and methods) are underlined.
Methods that are declared but not defined (abstract methods or those declared in interfaces) are in italics.
The names of abstract classes are in italics.
Dotted arrows with triangular heads point to interfaces from the classes that implement them.
Solid arrows with triangular heads go from classes to their parents.
Solid arrows with simple heads indicate has-a relationships (composition). The containing class is at the tail of the arrow and the class that is contained is at the head. The arrow is decorated with the access and name of the member in the containing class. The arrow is also decorated with the "multiplicity" of the relationship, where 0..1 means there is 1 instance of the member in the containing class and 0..* means there are many (usually indicating a collection such as an array or ArrayList).
Our UML diagram has some additional graphic notation:
A red square (empty or solid) in front of a name means private. (See Seat.label.)
A gold diamond in front of a name means protected. (See TrainCar.initSeats.)
A green circle in front of a name means public. (See Seat.reserve.)
SF in front of a name means static, final. (See FirstClassCar.NUM_ROWS.)
Methods embellished with C are constructors. (See Seat.Seat.)
You can read this UML class diagram and see the names and types of all the class members. The method signatures in your program must match the above diagram and provided interfaces exactly for the teaching staff tests to run.
Implementation
We suggest that you approach writing code for this project, one class at a time. Start with the classes that least depend on the others.
train_travel.transportation
Seat is independent of every class. It should implement Comparable, where Comparable is from in the Java API.
Attributes/State: Seat has a label (row and letter, such as 12A or 6C [U2, S1]), a trainID to indicate the number of the train car that the seat is on [UC1, S2], and its reserved status. (Note that train numbers are not array indexes; their range is 1 through the length of the train.)
Behaviors/Methods:
Seat(String, int) has two parameters, which initialize the label and train car number. Seats start out unreserved.
release() makes the Seat unreserved [UC7, S3][UC8, S3]. reserve() makes the Seat reserved [UC2, S4-7][UC5, S7][UC7, S3].
toString() returns a string representation of the seat in the form -. For example, 1-1A (first seat in car #1) and 2-3B (seat B in the third row of car#2).
compareTo(Seat) compares two Seats based on their - order. The comparison is first on the car#. If the two numbers are the same, then the comparison is on rows, and finally on seats across the row. (This comparison method is really helpful in sorting an array of seats [UC9, S2]).
TrainCar is an abstract class representing an individual car on a train.
Attributes/State: TrainCar has a number [UC1, S2], which is fixed and initialized in the constructor.
Behaviors/Methods: The constructor takes an int to initialize the id number for this car.There are four abstract methods:
openSeatsLeft() returns the number of seats on this car that are not already reserved [UC3], [UC5].
seatFor(int, int) returns the seat in the row (first parameter) and column (second parameter), where row and column are 0-based indexes for a two-dimensional array of Seats (declared in child classes) [UC3, S4-6], [UC5, S7]. Throws an IllegalArgumentException if row, column are out of range.
seatFor(String) returns the seat with the given label (see description of Seat.label above) [UC7, S3]. Throws an IllegalArgumentException if there is no seat with that label on this car.
getSeatMap() returns a string representation of the seating map for the car. Note that return value shows both the map label (car type, number) and the seating arrangement. See [UC2] for the exact formatting.
The three protected methods are used by the child classes. (They are a result of refactoring methods that would otherwise be duplicated in the children.)
initSeats() initializes the seats in a two-dimensional array with their labels and the car number.
drawSeatChart() returns a string representation of the actual seating map based on a two-dimensional array of strings and the location/index of the aisle. (The location is 1 for a First Class car, 2 for a Second Class car.) This method can be called by the child class implementations of getSeatMap().
seatFor(String, Seat[][]) returns the seat with the given label on the given 2-d array. Throws an IllegalArgumentException if the label is improper for this car.
FirstClassCar and SecondClassCar are similar concrete children of TrainCar.
Attributes/State: NUM_ROWS and NUM_SEATS_PER_ROW are static, final. and defined according to [UC2, S1].
CAPACITY is the number of passengers the car can seat [UC3, E3], [UC5, E4]. It is static, final.
RESERVE_LIMIT is the number of passengers a Second Class car can hold [UC4, S4]. It is static, final.
seats is a two-dimensional array of Seats. It is an instance variable initialized in the constructor.
Behaviors/Methods: Besides the constructor, the only public instance methods correspond to the abstract methods defined in the parent. Static methods:
getNumRows() and getNumSeatsPerRow() are simple getters for the correspondingly named instance variables.
getCapacity() returns the number of passengers the car can hold.
BicycleTransportCar is a concrete child of TrainCar.
CAPACITY is the number of bicycle passengers the car can hold [UC6, S4]. It is static, final.
Behaviors/Methods: Besides the constructor, the only public instance methods correspond to the abstract methods defined in the parent.
Both seatFor() methods throw IllegalArgumentException when called.
getCapacity() returns the number of passengers with bicycles the car can hold.
Train is a concrete class representing a train with First Class, Second Class, and Bicycle Transport cars.
Attributes/State: MIN_CARS and MAX_CARS are static, final. and defined according to [UC1, S1].
car is the the array of train cars that comprise the train.
numFirstClassCars is the number of First Class cars on this train.
The remaining instance variables keep track of the number of each type of reservation for this train.
Behaviors/Methods:
The constructor creates a new Train based on its parameter, which is the number of cars [UC1, S2]. Throws an IllegalArgumentException if the number is out of range [UC1, E3].
incReservationTypePassengers(int) increments the number of ReservationType passengers by the amount of the parameter and returns the new passenger count [UC3-6][UC8].
getSeatFor() methods have an int parameter that comes before the parameters for the corresponding TrainCar.getSeatFor() methods. The first int parameter is the index of the TrainCar (in the car[] array) that determines which TrainCar.getSeatFor() is called [UC7, S3]. Throws an IllegalArgumentException if the parameters are invalid [UC7, E2-3].
hasReservationTypeRoomFor(int) methods determine if the train can take an additional number of the ReservationType passengers as specified by the parameter [UC4, E3], [UC6, E4].
openTrainCarTypeSeats() methods give the number of unreserved seats in the corresponding Train Car Types of cars on this train [UC3, E3], [UC5, E3].
isTrainCarTypeCar(int) methods determine if the car at the index given by the parameter is the specified Train Car Type [UC7, E3].
getCarSeatMap(int) returns the seat map of the car at the index given by the parameter [UC2].
train_travel.tickets
Reservation is the abstract class that is the root of a hierarchy to represent reservations for train travel.
Attributes/State: MAX_PASSENGERS is static, final. and defined according to [UC3-6, E2].
number is static with an initial value of 1000. It's used to determine the number of the next reservation to be created [UC3, S3].
reservationID is an instance variable for the id of this reservation.
myTrain is a protected instance variable. The parameter to the Reservation constructor initializes it. The child classes can access it.
Behaviors/Methods: Except for the constructor and the getters, all methods are abstract or protected (plus optional private methods).Abstract methods:
chooseSeats() reserves/assigns seats for this reservation based on rules in [UC3, S4-6], [UC5, S7]. Throws an IllegalArgumentException if there are not enough seats.
changeSeats(String) releases the seats currently assigned to this reservation and reserves the seats represented by the parameter [UC7, S2-3]. Throws an IllegalArgumentException if the string does not represent seats valid for this reservation [UC7, E2-4].
cancel() releases any seats assigned to this reservation and frees passenger space (reduces passenger count) on the train according to the number of passengers for this reservation [UC8].
toPrint() returns a string representation for the reservation, formatted according to [UC9, S2].
Protected methods:
parseSeats(String) returns an array of Seats that the string parameter represents. The format of the paramater must match the description in [UC7, S2-3]. Throws an IllegalArgumentException if the format does not match.
reassignSeats(Seat[], Seat[]). Assigns new seats to the reservation and releases the current ones. The first parameter is an array of Seats to assign and the second parameter is the current array of Seats. The return value is the new seat assignment. Throws an IllegalArgumentException if the new seats are not valid [UC7, E2-4].
ComfortClass, EconomyClass, and BicycleClass are children of Reservation. They each have private constructors, and they rely on their public static newReservation(int, Train)methods to create new instances, where the first parameter is the number of passengers and the second is the train for this reservation. Those methods will throw IllegalArgumentExceptions if the number of passengers it out of range or the train cannot accommodate the passengers.
Attributes/State: BicycleClass has no attributes.
theSeats is the array of Seats assigned/reserved for this reservation.
reservedSeats belongs to EconomyClass only. It is a flag to indicate if seats are reserved.
Behaviors/Methods: The only non-private methods are those declared in Reservation. BicycleClass.changeSeats() and BicycleClass.chooseSeats() should always throw IllegalArgumentExceptions.
train_travel.manager
ReservationManager, which is the only class in this package, must define the behaviors declared in the TicketMaster interface. ReservationManager is the only class in the model that the GUI knows about.
Attributes/State:
theTrain is the only train for managing all of the reservations.
theReservations maintains the reservations in a list, sorted by reservation IDs. Its type is ArrayList.
Behaviors/Methods: See the documentation in the TicketMaster interface. Use the following details to customize those behaviors to ReservationManager.
The constructor has an int parameter, which determines the number of cars in the train [UC1, S1]. It throws an IllegalArgumenException if the number is not in range [UC1, E3].
makeNewReservation(int, String). The second parameter should be a string in the form "C" or "F", "E" or "S", or "B" corresponding to either reservation type or train car type. Throws an IllegalArgumenException if anything goes wrong (such as bad parameters or the train not able to accommodate the reservation request). See [UC3-6].
cancelReservation(String). The parameter is a string that starts with a reservation ID. Throws an IllegalArgumenException if there is no reservation with that ID on the list. Canceled reservations should be removed from the reservation list. See [UC8].
changeSeats(String, String). Documentation is provided in the TicketMaster interface. See [UC7].
printReservationList() returns a string of reservations formatted as shown in the Reservations scrolling list in Figure 1. See [UC9].
train_travel.ui
TrainTravelGUI is the front end of the program that the user sees and interacts with. Use this to do black box functional testing on your own code. The model, which contains the TicketMasterinterface and the classes that you must create, constitutes the back end.
The only data member from the model that TrainTravelGUI has is myReservations (declared type TicketMaster).
Implementation Process
Follow these steps and strategies as you implement your solution:
Compile a skeleton. The class diagram provides a full skeleton of what the implemented Train Travel program should look like. Copy in provided code and create the skeletons of the classes you will implement. Ensure that the packages, class names, and method signatures match the class diagram exactly! If a method has a return type, put in a place holder (for example, return 0; or return null;) so that your code will compile. Push to GitHub and make sure that your Jenkins job shows a yellow ball. A yellow ball on Jenkins means that 1) your code compiles and 2) that the teaching staff tests compile against your code, which means that you have the correct code skeleton for the design.
White Box Testing
Your JUnit tests should follow the same package structure as the classes that they test. You need to create JUnit tests for all of the classes that you create. At a minimum, you must exercise every method in your solution at least one by your JUnit tests. You will likely cover the simple getters, setters, and constructors as part of testing more complex functionality in your system. Start by testing all methods that are not simple getters, simple setters, or simple constructors for all of the classes that you must write and check that you're covering all methods. If you're not, write tests to exercise unexecuted methods.
For each method and constructor that throws exceptions, test to make sure that the method does what it is supposed to do and throws an exception when it should.
TicketMaster:-
/** * TicketMaster describes the behaviors needed to manage reservations for a train. * */ public interface TicketMaster { /** * Create a new reservation. * @param numPassengers number of passengers on the new reservation * @param kind determines which kind of reservation to create * @return the newly created reservation */ Reservation makeNewReservation(int numPassengers, String kind); /** * Cancel a reservation. * @param reservationString determines which reservation to cancel */ void cancelReservation(String reservationString); /** * Change seats for a reservation. * @param reservationString determines which reservation to change * @param newSeats a string representation of the new seats to assign to the reservation */ void changeSeats(String reservationString, String newSeats); /** * Show the list of current reservations as a string. * @return a string representation of the reservation list */ String printReservationList(); /** * Show a seating map for a train car. * @param idx index for which train map to show * @return a string representation of the train car map. */ String showMap(int idx); /** * How many seat maps are there? * @return the number of seat maps */ int numberOfSeatMaps(); }
TrainTravelGUI
import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.StringTokenizer; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; /** * This is the user interface for a train reservation system. It opens by asking the user to specify * the size of the train (number of train cars) for this system. Then it enables users to: 1) add new * reservations, 2) delete existing reservations, 3) change seating assignments. The left side of the * main window shows the train cars' seat maps. * * * */ public class TrainTravelGUI extends JFrame implements ActionListener { // Window, button, and scrollpane strings private final static String TITLE = "Train Reservation System"; // Main window title private final static String RESERVATIONS = "Reservations"; // Reservation list title private final static String SEAT_MAP = "Seating Map"; // Seating map title private final static String DELETE = "Delete Selected Reservation"; // Delete message/label private final static String ADD = "Add New Reservation"; // Add message/label private final static String QUIT = "Quit"; // Quit message/label private final static String LAST = "<--"; // Go back label private final static String NEXT = "-->"; // Go forward label private final static String FIRST_CLASS = "Comfort Class"; // Choice for Comfort Class tickets private final static String SECOND_CLASS = "Economy Class"; // Choice for Economy Class tickets private final static String BICYCLE = "Bicycle Class"; // Choice for Bicycle Class tickets private final static String PASSENGER_COUNT = "Number of Passengers:"; //Number of Passengers on Reservation: "; private final static String PREFERENCE = "Reserved Seats"; // Reserved Seats message/label private final static String RESERVATION_KIND = "Kind: "; // Reservation kind message/label private final static String CHANGE = "Change Seats on Selected Reservation"; // Seat change message/label private final static String NUM_CARS = "Number of train cars: "; // Number of train cars message/label private final static Object[] HINTS = {"Enter each seat as: -", "Separate seats by commas.", "For example: 1-2A,1-2B,2-17A"}; // Seat change dialog message private final static String[] RESERVATION_CLASS = {FIRST_CLASS, SECOND_CLASS, BICYCLE}; // Size constants for the window and scroll panes private final static int FRAME_WIDTH = 775; // Width of main window private final static int FRAME_HEIGHT = 650; // Height of main window private static final int RESERVATION_HEIGHT = 100; // Height of reservation display private static final int MAP_WIDTH = 27; // Width of seat map display private static final int MAP_HEIGHT = 23; // Height of seat map display private static final int PAD = 10; // Panel padding // Panels, Boxes, and Borders private TitledBorder bdrReservations = new TitledBorder(RESERVATIONS); // Reservation panel border private TitledBorder bdrSeatMap = new TitledBorder(SEAT_MAP); // Border around the seat map private JPanel pnlLeftSide = new JPanel(); // Holds seating map, entry fields on the left side of the window private JPanel pnlReservations = new JPanel(); // Shows reservations private JPanel pnlEntry = new JPanel(); // Holds data entry widgets private JPanel pnlMap = new JPanel(); // Holds map and data entry widgets private GridBagLayout gridbag = new GridBagLayout(); // Applied to pnlEntry private GridBagLayout gridbagCar = new GridBagLayout(); // Applied to pnlMap private GridBagConstraints gbc = new GridBagConstraints(); // Constraints on pnlEntry private GridBagConstraints gbsc = new GridBagConstraints(); // Constraints on pnlMap // Buttons private JButton btnDelete = new JButton(DELETE); // Remove a reservation private JButton btnAdd = new JButton(ADD); // Add a new reservation private JButton btnChange = new JButton(CHANGE); // Change a reservation private JButton btnLast = new JButton(LAST); // Show the previous train car seating chart private JButton btnNext = new JButton(NEXT); // Show the next train car seating chart private JButton btnQuit = new JButton(QUIT); // Quit the application // Labels for new reservation/passenger widget display private final JLabel lblPassengerCount = new JLabel(PASSENGER_COUNT); // Label for text field (number of passengers) private final JCheckBox cbxReserve = new JCheckBox(PREFERENCE, true); // Main window checkbox on reserved seats private final JLabel lblReservationKind = new JLabel(RESERVATION_KIND); // Label for type of reservation desired private final JLabel lblBlank = new JLabel(""); // Blank label (used for widget alignment // Field, combo box, radio buttons for new passenger reservation entry private JTextField txtNumber = new JTextField(); // For entry of #passengers on a new reservation private JComboBox cmbTicketType = new JComboBox(RESERVATION_CLASS); // Choice of reservation types private JLabel[] lblPassenger = { lblPassengerCount, lblReservationKind, lblBlank }; // Labels on new passenger widgets private Component[] cmpPassenger = { txtNumber, cmbTicketType, cbxReserve}; // New passenger widgets // Seating map display private JTextArea txtSeatMap = new JTextArea(MAP_WIDTH, MAP_HEIGHT); // Text area for seating map display // Scrolling list of reservations private DefaultListModel dlmReservations = new DefaultListModel<>(); // Default list model for reservation display private JList lstReservations = new JList<>(dlmReservations); // Reservation list to display private JScrollPane scrollReservations = new JScrollPane(lstReservations); // Scrollpane to hold the reservation display // Backend model private TicketMaster myReservations; // Manages reservations for this application private int mapNumber = 0; // Determines which car map is currently shown /** * Constructor. Sets up the user interface and initializes the backend model. */ public TrainTravelGUI() { initBackend(); initUI(); this.setVisible(true); } /** * Main method -- begins program execution. * @param args not used */ public static void main(String[] args) { new TrainTravelGUI(); } // ------ Controller Methods --------------------------- /** * Defines actions to be performed on button clicks * @param e button click (user event) */ public void actionPerformed(ActionEvent e) { if (e.getSource().equals(btnQuit)) // Quit the application. endExecution(); if (e.getSource().equals(btnDelete)) { // Delete the selected application. try { checkSelection(lstReservations.getSelectedIndex()); String reservation = lstReservations.getSelectedValue(); myReservations.cancelReservation(reservation); loadReservationList(); loadSeatMap(mapNumber); clearFields(); } catch (IllegalArgumentException noSelection) { JOptionPane.showMessageDialog(this, noSelection.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } if (e.getSource().equals(btnAdd)) { // Add a new reservation. String ticketClass = RESERVATION_CLASS[cmbTicketType.getSelectedIndex()]; try { int numPassengers = Integer.parseInt(txtNumber.getText()); Reservation r = myReservations.makeNewReservation(numPassengers, ticketClass); if (cbxReserve.isSelected()) r.chooseSeats(); } catch (NumberFormatException badNumber) { JOptionPane.showMessageDialog(this, "Number of passengers must be an integer.", "Error", JOptionPane.ERROR_MESSAGE); } catch (IllegalArgumentException badData) { JOptionPane.showMessageDialog(this, badData.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } loadSeatMap(mapNumber); loadReservationList(); clearFields(); } if (e.getSource().equals(btnChange)) { // Change the seating assignments on the selected reservation. try { checkSelection(lstReservations.getSelectedIndex()); String newSeats = JOptionPane.showInputDialog(null, HINTS, CHANGE, JOptionPane.INFORMATION_MESSAGE); if (newSeats == null) // User cancelled operation return; myReservations.changeSeats(lstReservations.getSelectedValue(), newSeats); loadReservationList(); loadSeatMap(mapNumber); } catch (IllegalArgumentException noSelection) { JOptionPane.showMessageDialog(this, noSelection.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } if (e.getSource().equals(btnLast)) { // Scroll to the previous seat map if (mapNumber > 0) mapNumber--; loadSeatMap(mapNumber); } if (e.getSource().equals(btnNext)) { // Scroll to the next seat map if (mapNumber < myReservations.numberOfSeatMaps() - 1) mapNumber++; loadSeatMap(mapNumber); } } // --------End Controller Methods --------------------- // ------ Private Methods ----------------------------- /** * Private method - Initializes the user interface. */ private void initUI() { // Set up the panels and the lists that make the UI setUpPanels(); setUpLists(); // Construct the main window and add listeners. setTitle(TITLE); setSize(FRAME_WIDTH, FRAME_HEIGHT); Container c = getContentPane(); c.add(pnlLeftSide, BorderLayout.WEST); c.add(pnlReservations, BorderLayout.CENTER); setVisible(true); addListeners(); // Make sure the application quits when the window is closed. addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { endExecution(); } }); } /** * Private method - Sets up the scrolling list of reservations. */ private void setUpLists() { // Load the data. loadReservationList(); lstReservations.setFont(new Font("Courier", Font.PLAIN, 12)); lstReservations.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } /** * Private method - Sets up the seating chart. */ private void setUpSeatingMap() { txtSeatMap.setEditable(false); txtSeatMap.setFont(new Font("Courier", Font.PLAIN, 12)); txtSeatMap.setBorder(bdrSeatMap); pnlLeftSide.add(pnlEntry); loadSeatMap(0); } /** * Private method - Sets up the panels for showing and modifying reservations */ private void setUpNewReservations() { // Set up the right side of the window in pnlReservations. // Initialize the reservation list. scrollReservations.setBorder(bdrReservations); scrollReservations.setPreferredSize(new Dimension(FRAME_WIDTH / 2 - 4 * (PAD), RESERVATION_HEIGHT)); pnlReservations.setLayout(new BorderLayout()); pnlReservations.setBorder((EmptyBorder) BorderFactory .createEmptyBorder(PAD, PAD / 2, PAD, PAD)); // Lay out the buttons and reservation entry fields in a grid. pnlEntry.setLayout(gridbag); pnlEntry.setBorder((EmptyBorder) BorderFactory.createEmptyBorder( PAD, PAD / 2, PAD, PAD)); // Fill the first row with the seating map gbc.anchor = GridBagConstraints.PAGE_START; gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.ipady = 0; gbc.insets = new Insets(1, 0, 0, 0); gbc.fill = GridBagConstraints.NONE; pnlEntry.add(pnlMap, gbc); // Second row is a horizontal separator gbc.gridy++; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = 2; pnlEntry.add(new JSeparator(JSeparator.HORIZONTAL), gbc); // The next three rows are for user input of new reservation information gbc.gridy++; gbc.fill = GridBagConstraints.NONE; gbc.gridwidth = 1; int numLabels = lblPassenger.length; gbc.anchor = GridBagConstraints.EAST; for (int i = 0; i < numLabels; i++) { gbc.gridx = 0; gbc.gridy++; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0.0; pnlEntry.add(lblPassenger[i], gbc); gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0; pnlEntry.add(cmpPassenger[i], gbc); cbxReserve.setSelected(false); } // Now add the remaining three buttons gbc.anchor = GridBagConstraints.LINE_START; gbc.fill = GridBagConstraints.NONE; gbc.gridwidth = 2; gbc.gridx = 0; gbc.gridy++; pnlEntry.add(btnAdd, gbc); gbc.gridy += 1; gbc.gridx = 0; gbc.fill = GridBagConstraints.HORIZONTAL; pnlEntry.add(new JSeparator(JSeparator.HORIZONTAL), gbc); gbc.anchor = GridBagConstraints.LINE_START; gbc.gridy += 1; gbc.fill = GridBagConstraints.NONE; pnlEntry.add(btnChange, gbc); gbc.gridy++; gbc.gridwidth = 2; gbc.ipady = 0; gbc.fill = GridBagConstraints.NONE; pnlEntry.add(btnDelete, gbc); } /** * Private method - Determines the geometry of the main window. */ private void setUpPanels() { pnlLeftSide.setLayout(new BorderLayout()); pnlMap.setLayout(gridbagCar); gbsc.anchor = GridBagConstraints.PAGE_START; gbsc.gridx = 0; gbsc.gridy = 0; gbsc.gridwidth = 2; gbsc.insets = new Insets(5, 0, 0, 0); gbsc.fill = GridBagConstraints.NONE; pnlMap.add(txtSeatMap, gbsc); gbsc.gridy = 1; gbsc.gridwidth = 1; pnlMap.add(btnLast, gbsc); gbsc.gridx = 1; pnlMap.add(btnNext, gbsc); setUpSeatingMap(); setUpNewReservations(); // Put the reservations, quite button on the right side of the window. pnlReservations.add(scrollReservations, BorderLayout.CENTER); pnlReservations.add(btnQuit, BorderLayout.SOUTH); pnlLeftSide.add(pnlEntry, BorderLayout.CENTER); } /** * Private Method - Adds listeners to the buttons. */ private void addListeners() { btnDelete.addActionListener(this); btnAdd.addActionListener(this); btnLast.addActionListener(this); btnNext.addActionListener(this); btnChange.addActionListener(this); btnQuit.addActionListener(this); } /** * Private method - Clears text field sets the seat selection check box to unchecked. */ private void clearFields() { txtNumber.setText(""); cbxReserve.setSelected(false); } /** * Private Method - Loads the reservation list model from a string with newline delimiters. */ private void loadReservationList() { dlmReservations.clear(); StringTokenizer st = new StringTokenizer(myReservations.printReservationList(), " "); while (st.hasMoreTokens()) { dlmReservations.addElement(st.nextToken()); } } /** * Private method - Loads the seating map for the given car. * @param k index of the car map to be loaded */ private void loadSeatMap(int k) { if (k >= 0 && k < myReservations.numberOfSeatMaps()) { String seats = " " + myReservations.showMap(k); txtSeatMap.setText(seats); } } /** * Private method - Initializes the backend model. */ private void initBackend() { String aNumber = JOptionPane.showInputDialog(this, "Number of train cars", NUM_CARS, JOptionPane.INFORMATION_MESSAGE); if (aNumber == null || aNumber.length() == 0) endExecution(); try { myReservations = new ReservationManager(Integer.valueOf(aNumber.trim())); } catch (IllegalArgumentException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); endExecution(); } } /** * Private method - Makes sure an item (reservation) is selected. * @param selectedIndex */ private void checkSelection(int selectedIndex) { if (selectedIndex < 0) throw new IllegalArgumentException("No reservation selected."); } /** * Private Method - Ends execution of the program. */ private void endExecution() { System.exit(0); } // ------------- End Private Methods ------------------- } Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
