2011-03-29 83 views
0

聲明:這是一個(令人沮喪的)作業相關的問題。需要幫助查找此if語句中的錯誤

我在屏幕上繪製我的對象時有奇怪的結果。我想這...我畫第一個對象,然後畫第二個對象,當我選擇第三個對象畫畫面清除,我必須再次啓動過程....我得到的是...我畫第一個對象,我畫第二個對象,我去繪製第三個對象屏幕清除...我選擇第三個對象,但SECOND對象是出現在屏幕上。請幫助指向正確的方向。

package ui.panels; 

import java.awt.Choice; 
import java.awt.Panel; 
import java.awt.event.ItemEvent; 
import java.awt.event.ItemListener; 
import model.Model; 
import interfaces.Resettable; 

public class ChoicePanel extends Panel implements Resettable{ 
    public int i = 0; 
    /** 
    * 
    */ 
    private static final long serialVersionUID = 1L; 
    Model model; 
    Choice selection; 

    public ChoicePanel(Model mdl) { 
     model = mdl; 
     selection = new Choice(); 
     for (String msg : Model.selections) { 
      selection.add(msg); 
     } 
     selection.addItemListener(new ItemListener() { 

      public void itemStateChanged(ItemEvent e) { 
      if(i==1) {//drop down clicked three times) 
       System.out.println("ChoicePanel says i == "+i); 
       model.setMessage(selection.getSelectedItem()); 
       model.setCurrentShapeType(selection.getSelectedItem()); 
       //model.repaint(); 
       ++i; 
      }else if(i==2){ 
       System.out.println("ChoicePanel says i == "+i); 
       model.setMessage(selection.getSelectedItem()); 
       //model.setCurrentShapeType(selection.getSelectedItem()); 
       model.resetComponents(); 
       //--i; 
      }else{ 
       model.setMessage(selection.getSelectedItem()); 
       //this line is what sends a value to shape that is drawn on screen 
       model.setCurrentShapeType(selection.getSelectedItem()); 
       //model.repaint(); 
       ++i; 
      } 
      } 

     }); 
     this.add(selection); 
    } 

    public void resetComponents() { 
    System.out.println("resetComponents from ChoicePanel"); 
    //this resets the drop down list selection array to the first choice on the list 
    selection.select(0); 
    //this sets selected item in the selection array set in the above line 
    //model.setMessage(selection.getSelectedItem()); 
    i=0; 
    model.repaint(); 
    } 

} 
+0

在新的ItemListener()範圍內是否存在「i」? – 2011-03-29 21:31:28

+0

是的,因爲「我」是封閉類的領域(儘管可能不是很好的風格,尤其是因爲它是公開的)。 – Thomas 2011-03-29 21:37:32

回答

3

else if(i==2){ ... }你不增加i,它永遠不會讓過去2

} else if(i==2){ 
    System.out.println("ChoicePanel says i == "+i); 
    model.setMessage(selection.getSelectedItem()); 
    //model.setCurrentShapeType(selection.getSelectedItem()); 
    model.resetComponents(); 
    ++i; // Increment here 
} 
+0

...並且在第三個狀態到達後不應該將i重置爲0嗎? – 2011-03-29 21:34:50

+0

是的,我在model.resetComponents()中設置爲0; (它位於上面貼出的代碼的底部) – thefonso 2011-03-29 22:56:05