【问题标题】:Edit an object in an ArrayList (Java Swing/GUI)编辑 ArrayList 中的对象 (Java Swing/GUI)
【发布时间】:2015-02-12 12:02:43
【问题描述】:

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

首先,Passenger 从 Person、Date 和 Name 3 个类继承其详细信息。乘客的详细信息是自动递增的唯一 ID、头衔、名字、姓氏、出生日期(日、月、年)、行李数量和优先登机。这是乘客继承详细信息的代码。

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,它实际上并没有检查乘客是否正确存在。我也明白我实际上什至没有调用 edit 方法,但我也无法使用该方法使其工作。

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

【问题讨论】:

    标签: java swing user-interface arraylist


    【解决方案1】:

    使用字符串很简单,但我认为问题是你不知道如何真正使用数组列表。

    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()]);
    }
    

    【讨论】:

      【解决方案2】:

      我不确定您的 editForGUI 方法不是很清楚。我假设当您更新乘客详细信息并单击编辑乘客时,它应该更新列表。如果是这种情况,那么试试这个..

      1. 如果您在方法中使用 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;
      }
      }
      }
      

      `

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

      【讨论】:

      • 是的,就是这个想法,我的想法是循环遍历数组列表乘客,如果输入的 ID 是数组列表中的对象之一的 ID,我将能够设置乘客对象并在数组列表中更新该乘客。
      • 很抱歉您的帖子让我感到困惑。但无论如何,我将在下面发布如何编辑数组列表中的值。
      • 是的,然后继续使用我提供的代码..它将更新集合中的乘客对象..
      • 我已经添加了您的代码,但是对于 Passenger p = Passengers.get(i) 行,它显示此错误 --> 类型不匹配:无法从对象转换为乘客。知道为什么会发生这种情况吗?
      • 请告诉我旅客集合的声明和初始化?这个集合包含什么类型的对象?可能您想将您的收藏修改为 List 乘客 = new ArrayList
      【解决方案3】:

      我相信您的 ArrayList 问题出在这一行:

      passengers.set(id, passenger);
      

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

      set(int index, E element)
      

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

      【讨论】:

        猜你喜欢
        • 2015-09-11
        • 1970-01-01
        • 2014-05-05
        • 1970-01-01
        • 2012-08-12
        • 2011-07-08
        • 2010-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多