2016-04-08 19 views
0

'order_List'からアイテムを削除する削除ボタンを作成しようとしています。私が 'removeButton'を作成したボタンは、リストから1つの項目だけを削除し、その後にエラーメッセージを表示します。リストからアイテムを削除する削除ボタンを作成しようとしています

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) 
+0

ええ、あなたが見ているエラーメッセージは何ですか? – Mordechai

+1

変数名は大文字で始めるべきではありません。あなたの変数の中には正しいものがあります。一貫してください!クラス名は大文字で始めるべきです(SHOULD)。フォーラムでは、あなたが従わないJavaの規約に基づいてハイライトを表示するので、あなたのコードは非常に読みにくいです。 – camickr

答えて

3
int selectionNumber = meal_List.getSelectedIndex(); 

あなたは "meal_List" から選択したインデックスを取得します。

listOrder.removeElementAt(selectionNumber); 

ただし、「listOrder」から項目を削除しようとしました。

両方のステートメントに同じJListを使用し、一貫性を保ちます。

また、名前付けと一貫してください。なぜあなたはJList名の1つに "_"を使用していますか?変数名にはアンダースコアを使用しないでください。いくつかの基本については、Java conventionsをチェックしてください。

+0

ありがとうございました。私はJavaの規約をチェックし、すべてのコードを一貫して保つようにします。 –

+0

私が持っているこの他の問題を見てもらえますか? http://stackoverflow.com/questions/36507397/trying-to-pass-multiple-values-into-a-label –

+0

@MatthewRichardson:stackoverflowヘルプセクションを読んでください:[誰かが私の質問に答えたときにどうするか](http ://stackoverflow.com/help/someone-answers)。 –

関連する問題