简体   繁体   English

编辑ArrayList中的对象(Java Swing / GUI)

[英]Edit an object in an ArrayList (Java Swing/GUI)

I'm currently working on a simple GUI system in Java using Swing and I am trying to edit a Passenger. 我目前正在使用Swing在Java中使用简单的GUI系统,我正在尝试编辑Passenger。 The passenger is an object that is stored in an arrayList. 乘客是存储在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. 我目前用于编辑方法的代码是完美的,例如,If / Elses可能实际上不起作用,但我需要的是关于如何使实际方法进行/工作的建议。

Firstly, the Passenger inherits its details from 3 classes, Person, Date and Name. 首先,Passenger从3个类,Person,Date和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. 乘客的详细信息是自动递增的唯一ID,标题,名字,姓氏,DOB(日,月,年),行李数量和优先登机。 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. 然后我有一个PassengerFileHandler类,它具有我需要的GUI方面的所有方法,例如添加/删除乘客等等。这是我在PassengerFileHandler类中的编辑方法。 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. 然后我进入我的实际框架类,我在那里制作GUI并调用方法。 To call the methods I made an instance of the passengerFileHandler class by typing the following 要调用方法,我键入以下内容来创建passengerFileHandler类的实例

final PassengerFileHandler pfh = new PassengerFileHandler();

Here is where I make the Edit button and do the ActionListener for the JButton. 这是我创建Edit按钮并为JButton执行ActionListener的地方。

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. 我非常确定其中一个更大的问题是,当我执行代码时,我要求用户提供他们希望编辑的乘客的ID,但实际上并未检查Passenger是否存在正确。 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. 这些图像可以帮助您了解GUI的外观以及代码可能/可能不会执行的操作。 Image 1 is the GUI and how it looks with the buttons. 图1是GUI以及按钮的外观。 Image 2 is when you click the "Edit" button, the ID request pops up. 图2是当您单击“编辑”按钮时,会弹出ID请求。 Image 3 is where the user attempts to set the new passenger data. 图3是用户尝试设置新乘客数据的地方。

GUI Look

要求身份证

在哪里我要求新的细节

Simple enough it's with strings but I think the issue is you don't know how to really use an arraylist. 很简单,它是字符串,但我认为问题是你不知道如何真正使用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()]);
}

i am not sure about your editForGUI method a it is not very clear. 我不确定你的editForGUI方法是不是很清楚。 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 如果您在方法中使用updatedPassenger和Passsenger列表作为参数,则以下内容将起作用

` `

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? 为什么不使用HashMap代替列表? In-place update would be more efficient. 就地更新会更有效率。 id will be key and Passenger object will be the value in HashMap.. id将是key,Passenger对象将是HashMap中的值。

I believe your ArrayList problem is in this line: 我相信你的ArrayList问题在这一行:

passengers.set(id, passenger);

At this point, you have found the passenger that matches the id and you want to replace it. 此时,您已找到与id匹配的乘客,并且您想要替换它。 If you take a look at the ArrayList documentation, the method signature for set is 如果您查看ArrayList文档,则set的方法签名是

set(int index, E element)

The first parameter you pass is the index you want to set, not the id. 您传递的第一个参数是您要设置的索引,而不是ID。 However, since you used the enhanced for loop to iterate through the ArrayList, you don't know the index. 但是,由于您使用增强型for循环迭代ArrayList,因此您不知道索引。 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. 您可以使用您找到的乘客调用indexOf()方法来获取索引,但这样做效率很低,因为您只是遍历数组并且方法调用基本上会重复您刚才为获取索引而执行的所有操作。 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. 相反,您可以保留一个在if检查后递增的计数器,一旦找到它,计数器就会设置为您项目的索引。 Inside your if block, you can immediately set your passenger using that index and return right after. if区块内,您可以使用该索引立即设置乘客,然后立即返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM