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

时间:2014-12-14 04:18:08

标签: java swing user-interface arraylist

我目前正在使用Swing在Java中使用简单的GUI系统,我正在尝试编辑Passenger。乘客是存储在arrayList中的对象。涉及继承,因此还涉及多个类。我目前用于编辑方法的代码是完美的,例如,If / Elses可能实际上不起作用,但我需要的是关于如何使实际方法进入/工作的建议。

首先,Passenger从3个类,Person,Date和Name继承其详细信息。乘客的详细信息是自动递增的唯一ID,标题,名字,姓氏,DOB(日,月,年),行李数量和优先登机。以下是乘客继承细节的代码。

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;
}

然后我有一个PassengerFileHandler类,它具有GUI方面所需的所有方法,例如添加/删除乘客等等。这是我在PassengerFileHandler类中的编辑方法。 很可能是问题开始的地方,我相信这是制作方法以编辑对象的正确方法。

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

然后我进入我的实际框架类,我在那里制作GUI并调用方法。为了调用这些方法,我输入了以下

来创建了passengerFileHandler类的实例
final PassengerFileHandler pfh = new PassengerFileHandler();

这是我创建“编辑”按钮并为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
    }
}
});

我很确定其中一个更大的问题是,当我执行代码时,我要求用户提供他们希望编辑的乘客的ID,但实际上并未检查Passenger是否存在正确。我也明白我实际上甚至没有调用编辑方法,但我也无法使用该方法。

以下图片可帮助您了解GUI的外观以及代码可能/可能不会执行的操作。图1是GUI以及按钮的外观。图2是当您单击“编辑”按钮时,会弹出ID请求。图3是用户尝试设置新乘客数据的地方。

GUI Look

Asking for an ID

Where I ask for the new details

3 个答案:

答案 0 :(得分:2)

很简单,它有字符串,但我认为问题是你不知道如何真正使用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()]);
}

答案 1 :(得分:1)

我不确定你的editForGUI方法是不是很清楚。我假设当你更新乘客的详细信息并点击编辑乘客时,它应该更新列表..如果是这样的话那就试试吧..

  1. 如果您在方法中使用updatedPassenger和Passsenger列表作为参数,则以下内容将起作用
  2. `

    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;
    }
    }
    }
    

    `

    为什么不使用HashMap代替列表?就地更新会更有效率。 id将是key,Passenger对象将是HashMap中的值..

答案 2 :(得分:0)

我相信你的ArrayList问题就在这一行:

passengers.set(id, passenger);

此时,您已找到与该ID匹配的乘客,并且您想要替换它。如果您查看ArrayList文档,则set的方法签名为

set(int index, E element)

您传递的第一个参数是您要设置的索引,而不是ID。但是,由于您使用增强的for循环遍历ArrayList,因此您不知道索引。您可以调用indexOf()方法来使用您找到的乘客获取索引,但这样做效率很低,因为您只是遍历数组并且方法调用基本上会重复您刚才为获取索引而执行的所有操作。相反,您可以保留一个在if检查后递增的计数器,一旦找到它,计数器就会设置为您项目的索引。在if区块内,您可以立即使用该索引设置乘客,然后立即返回。