Matthew
Matthew

Reputation: 41

Trying to create a remove button which removes items from a list

I am trying to make a remove button which will remove an item from 'order_List'. The button that I have made 'removeButton' removes only one item from the list and after that brings up error messages.

    menulist listOrder = new menulist();

    order_List = new JList(listOrder);
    order_List.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
    order_List.setBounds(457, 72, 241, 105);
    contentPane.add(order_List);

    JButton order_Btn = new JButton();
    order_Btn.setText("Place Order");
    order_Btn.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            int selectionNumber = meal_List.getSelectedIndex();
            if (selectionNumber == -1){
                JOptionPane.showMessageDialog(MenuPage.this, "Please select a meal");
            } else {
                Food orderedMeal = (Food) meal_List.getSelectedValue();

                JOptionPane.showMessageDialog(MenuPage.this, "You have ordered "        //clear the last order . find a code to do that
                        + orderedMeal + "");
                listOrder.addElement(orderedMeal);
                }
        }

    });

    JButton removeButton = new JButton("remove");
    removeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
                int selectionNumber = meal_List.getSelectedIndex();
                if (selectionNumber == -1) {
            JOptionPane.showMessageDialog(MenuPage.this, "Remove  Item");
                } else {
                    listOrder.removeElementAt(selectionNumber);
                }
        }
    });
    removeButton.setBounds(585, 189, 117, 29);
    contentPane.add(removeButton);
    }   

error message that appears.

 Exception in thread "AWT-EventQueue-0"       java.lang.ArrayIndexOutOfBoundsException: 2 >= 1
at java.util.Vector.removeElementAt(Vector.java:558)
at javax.swing.DefaultListModel.removeElementAt(DefaultListModel.java:331)
at MenuPage$10.actionPerformed(MenuPage.java:293)

Upvotes: 0

Views: 90

Answers (1)

camickr
camickr

Reputation: 324207

int selectionNumber = meal_List.getSelectedIndex();

You get the selected index from the "meal_List".

listOrder.removeElementAt(selectionNumber);

But you try to delete the item from the "listOrder".

Be consistent and use the same JList for both statements.

Also, be consistent with naming. Why are you using an "_" in one of the JList names? Variable names should NOT contain an underscore. Check out Java conventions for some basics.

Upvotes: 3

Related Questions