开发者

trying to create a switch using if in java

开发者 https://www.devze.com 2023-02-19 03:09 出处:网络
This is a HW problem. I keep getting the following error on screen related to my if(i==3) statement...

This is a HW problem. I keep getting the following error on screen related to my if(i==3) statement...

"Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException at ui.panels.C开发者_运维问答hoicePanel$1.itemStateChanged(ChoicePanel.java:31)"

...Can someone point me in the right direction? Here is my code. Thanks for your time.

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) {

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

          public void itemStateChanged(ItemEvent e) {
            if(i==3) {//drop down clicked three times)
              System.out.println("PING");
            }else{
              model.setMessage(selection.getSelectedItem());
              //this line is what sends a value to shape that is drawn on screen
              //NOT line 36 of GUIDemo.java
              //
              model.setCurrentShapeType(selection.getSelectedItem());
              model.repaint();
              ++i;
            }

          }

      });
      this.add(selection);
  }

  public void resetComponents() {
    //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());
    //model.repaint();
  }

}


I believe you are not initializing model, which would give a NullPointerException when it was first dereferenced.


You did not initialize model. If i is not 3 the else-block will get executed, which contains model.setMessage(...) - but model does not yet "exist".

0

精彩评论

暂无评论...
验证码 换一张
取 消