尝试创建一个删除按钮,从列表中删除项目 [英] Trying to create a remove button which removes items from a list

查看:104
本文介绍了尝试创建一个删除按钮,从列表中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个删除按钮,该按钮会从'order_List'中删除一个项目。我制作的按钮'removeButton'只从列表中删除一个项目,之后会显示错误消息。

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

出现错误信息。

 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)


推荐答案

int selectionNumber = meal_List.getSelectedIndex();

您可以从meal_List获得所选索引。

You get the selected index from the "meal_List".

listOrder.removeElementAt(selectionNumber);

但您尝试从listOrder中删除该项目。

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

保持一致并对两个语句使用相同的JList。

Be consistent and use the same JList for both statements.

此外,与命名一致。为什么在其中一个JList名称中使用_?变量名称不应包含下划线。查看 Java惯例了解一些基础知识。

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.

这篇关于尝试创建一个删除按钮,从列表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆