1

I'm currently working on a simple GUI system in Java using Swing and I am trying to edit a Passenger. The passenger is an object that is stored in an arrayList. There is inheritance involved so there is also multiple classes involved. The code I currently have for the edit method is for from perfect eg If/Elses may not actually work but all I require is advice on how to get the actual method going/working.

Firstly, the Passenger inherits its details from 3 classes, Person, Date and Name. The details of the passenger are the unique ID which auto increments, the Title, Firstname, Surname, DOB (Day, month, year), number of bags and priority boarding. Here is the code where the passenger inherits the details.

public Passenger(String t, String fN, String sn, int d, int m, int y, int noB, boolean pB) 
{
    // Call super class constructor - Passing parameters required by Person
    super(t, fN, sn, d, m, y);

    // And then initialise Passengers own instance variables
    noBags = noB;
    priorityBoarding = pB;
}

I then have a PassengerFileHandler class that has all the methods that I will need for the GUI aspect of things eg Add/Delete passenger etc etc. Here is my edit method that I have in my PassengerFileHandler class. This is most likely where the problem starts, I believe this is the correct way to make a method for the purpose of editing an object.

 public Passenger editForGUI(int id, Passenger passenger) 
    {
        for (Passenger passengerRead : passengers) 
        {
            if (id == passengerRead.getNumber()) 
            {
                passengers.set(id, passenger);
            }
        }
        return null;
    }

I then go into my actual frame class that I have where I make the GUI and call the methods. To call the methods I made an instance of the passengerFileHandler class by typing the following

final PassengerFileHandler pfh = new PassengerFileHandler();

Here is where I make the Edit button and do the ActionListener for the JButton.

btnEditAPassenger.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
    try
    {

        editPanel = new JPanel();
        editPanel.setLayout(new GridLayout(9, 2));
        editPanel.setPreferredSize(new Dimension(280, 280));

        //Add radiobutton for priority
        JRadioButton yes1 = new JRadioButton();
        yes1.setText("Yes");
        JRadioButton no1 = new JRadioButton();
        no1.setText("No");

        ButtonGroup group1 = new ButtonGroup();
        group1.add(yes1);
        group1.add(no1);

        //Make an panel for the RadioButtons to be horizontal
        radioButtonPanel1 = new JPanel();
        radioButtonPanel1.setLayout(new GridLayout(1, 2));
        radioButtonPanel1.setPreferredSize(new Dimension(40, 40));

        radioButtonPanel1.add(yes1);
        radioButtonPanel1.add(no1);



        //title is a comboBox that is auto filled
        editPanel.add(new JLabel("Title : "));
        editPanel.add(editTitleComboBox = new JComboBox<String>());
        editTitleComboBox.addItem("Mr");
        editTitleComboBox.addItem("Ms");
        editTitleComboBox.addItem("Mrs");
        editTitleComboBox.addItem("Miss");

        //Add the firstName textfield
        editPanel.add(new JLabel("First name : "));
        editPanel.add(editFirstNameText = new JTextField(20));

        //Add the surname textfield
        editPanel.add(new JLabel("Surname : "));
        editPanel.add(editSurNameText = new JTextField(20));

        //Day is a comboBox that is auto filled
        editPanel.add(new JLabel("Day : "));
        editPanel.add(editDayComboBox = new JComboBox<Integer>());
        int days = 0;
        for(int i = 0; i < 31; i++)
        {
            days++;
            editDayComboBox.addItem(days);
        }

        //Month is a comboBox that is auto filled
        editPanel.add(new JLabel("Month : "));
        editPanel.add(editMonthComboBox = new JComboBox<Integer>());
        int months = 0;
        for(int i = 0; i < 12; i++)
        {
            months++;
            editMonthComboBox.addItem(months);
        }

        //Year is a comboBox that is auto filled
        editPanel.add(new JLabel("Year : "));
        editPanel.add(editYearComboBox = new JComboBox<Integer>());
        int yearNum = 2014 + 1 ;
        for(int i = 1900; i < yearNum; i++)
        {
            editYearComboBox.addItem(i);
        }

        //NumberOfBags is a comboBox that is auto filled
        editPanel.add(new JLabel("Number of Bags : "));
        editPanel.add(editBagsComboBox = new JComboBox<Integer>());
        int bags = 0;
        for(int i = 0; i < 10; i++)
        {
            bags++;
            editBagsComboBox.addItem(bags);
        }

        //Priority booking is a button group
        editPanel.add(new JLabel("Priority boarding : "));
        editPanel.add(radioButtonPanel1);

        String input1 = JOptionPane.showInputDialog(null,"Enter the ID of the passenger you wish to edit: ");

        if (input1 == null) 
        {
            JOptionPane.showMessageDialog(null,"You have decided not to edit a Passenger");
        }
        if (input1.length() <1) 
        {
            JOptionPane.showMessageDialog(null,"Invalid entry");
        }
        if (input1 != null) 
        {
            // Put a Border around the Panel        
            editPanel.setBorder(new TitledBorder("Edit Passenger Details"));    

            //Make custom buttons
            Object[] customButtonSet1 = {"Edit Passenger", "Cancel"};

            int customButtonClick1 = JOptionPane.showOptionDialog(null,editPanel,"Edit", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, customButtonSet1, customButtonSet1[1]);

            if(customButtonClick1 == JOptionPane.YES_OPTION)
            {
                try
                {
                    if(pfh.passengers.contains(Integer.valueOf(input1)))
                    {
                        Passenger myObj = pfh.passengers.get(Integer.valueOf(input1));

                        //Passenger passenger1 = pfh.list().get(String.valueOf(pfh.passengers.equals(input1))))
                        //JOptionPane.showMessageDialog(null, "Succesfully edited the Passenger");
                        String title1 = String.valueOf(editTitleComboBox.getSelectedItem());
                        String firstName1 = String.valueOf(editFirstNameText.getText());
                        String surName1 = String.valueOf(editSurNameText.getText());
                        int day1 = Integer.valueOf(editDayComboBox.getSelectedItem().toString());
                        int month1 = Integer.valueOf(editMonthComboBox.getSelectedItem().toString());
                        int year1 = Integer.valueOf(editYearComboBox.getSelectedItem().toString());
                        int numBags1 = Integer.valueOf(editBagsComboBox.getSelectedItem().toString());
                        boolean priority1;

                        //Method to get the boolean
                        if(yes1.isSelected())
                        {
                            priority1 = true;
                        }
                        else
                        {
                            priority1 = false;
                        }


                        myObj.setName(new Name(title1, firstName1, surName1));
                        myObj.setDateOfBirth(new Date(day1, month1, year1));
                        myObj.setNoBags(numBags1);
                        myObj.setPriorityBoarding(priority1);

                        //Makes the toString clean
                        String formatedString = (pfh.passengers.toString().replace("[", "").replace("]", "").trim());   

                        //refreshes the textArea and auto fills it with the current ArrayList
                        textArea.setText("");
                        textArea.append(formatedString);
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null, "Passenger does not exist");
                    }  
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Passenger does not exist");
            }
            if(customButtonClick1 == JOptionPane.CANCEL_OPTION || customButtonClick1 == JOptionPane.NO_OPTION)
            {
                JOptionPane.showMessageDialog(null, "You have decided not to Edit a Passenger");
            }
        }
    }
    catch (Exception ex) 
    {
        // do nothing
    }
}
});

I am pretty sure that one of the bigger issues is that when I do the code where I ask the user for the ID of the passenger they wish to edit it doesn't actually check if the Passenger exists correctly. I also understand that I don't actually even call the edit method but I couldn't get it working using the method either.

Here are images to help you understand what the GUI looks like and what the code may/may not be doing. Image 1 is the GUI and how it looks with the buttons. Image 2 is when you click the "Edit" button, the ID request pops up. Image 3 is where the user attempts to set the new passenger data.

GUI Look

Asking for an ID

Where I ask for the new details

3 Answers 3

2

Simple enough it's with strings but I think the issue is you don't know how to really use an arraylist.

public String[] currentArray = { "temp", "temp1", "temp3"};
public void addToList(String tobeadded) {
    ArrayList<String> temp = new ArrayList<String>();
    for(String s: currentArray) {
        temp.add(s);
    }
    temp.add(tobeadded);
    currentArray = temp.toArray(new String[temp.size()]);
}

public void removeFromList(String toRemove) {
    ArrayList<String> temp = new ArrayList<String>();
    for(String s: currentArray) {
        if(!toRemove.equals(s))
            temp.add(s);
    }
    currentArray = temp.toArray(new String[temp.size()]);
}

public void edit(String orginal, String new1) {
    ArrayList<String> temp = new ArrayList<String>();
    for(String s: currentArray) {
        if(!orginal.equals(s))
            temp.add(s);
    }
    temp.add(new1);
    currentArray = temp.toArray(new String[temp.size()]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

i am not sure about your editForGUI method a it is not very clear. I am assuming that when you update the passenger details and click on edit passenger, it should update list.. If that is the case then try this..

  1. If you are using updatedPassenger and Passsenger list as parameters in your method then the following will work

`

void editForGUI(Passenger updatedObject, List passengers){
for(int i=0; i<passengers.size; i++){
Passenger p = passengers.get(i);
if( p.getId() == updatedPassenger.getId()){
passengers.set(i, updatedObject);
return;
}
}
}

`

Why don't you use HashMap in place of list? In-place update would be more efficient. id will be key and Passenger object will be the value in HashMap..

8 Comments

Yeah, thats the idea, my thinking was to loop through the arraylist passengers and if the id entered was an id of one of the objects inside the arraylist i would be able to set the new data of the passenger object and update that passenger in the arraylist.
I am sorry your post confused me. But I am going to post how to edit a value from an arraylist below anyway.
Yes then go ahead and use the code that I gave.. It will update the passenger object in collection..
I have added your code but for the line Passenger p = passengers.get(i) it is showing this error --> Type mismatch: Cannot convert from Object to Passenger. Any idea why that would be occuring?
Can you please let me know the declaration and initialization of passengers collection? What type of object does this collection holds? may be you want to modify your collection to something like List<Passenger> passengers = new ArrayList<Passenger>
|
0

I believe your ArrayList problem is in this line:

passengers.set(id, passenger);

At this point, you have found the passenger that matches the id and you want to replace it. If you take a look at the ArrayList documentation, the method signature for set is

set(int index, E element)

The first parameter you pass is the index you want to set, not the id. However, since you used the enhanced for loop to iterate through the ArrayList, you don't know the index. You can call the indexOf() method to get the index using the passenger that you found, but that would be inefficient since you just iterated through the array and the method call would basically repeat everything you just did to get the index. Instead you can keep a counter that increments after the if check, and once you have found it, the counter is set to the index of your item. Inside your if block, you can immediately set your passenger using that index and return right after.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.