Java Checkers - 删除Icon,java.lang.NullPointerException

时间:2014-06-14 10:54:55

标签: java nullpointerexception icons

我的跳棋有问题,跳跳不起作用,我不知道我能做些什么可以工作,请帮忙或给我一些提示:)

public class DnD extends JFrame {

    private JPanel boardPane;
    Icon z = null;
    JLabel jlabel = new JLabel();
    String k="";
    String ballPressed="";
    String p="";

 public DnD(){
    super("Checker");

    icdim = new Dimension(greenIcon.getIconWidth() + 5, greenIcon.getIconHeight() + 5);
    boardPane = new JPanel();
    board = new JLabel[8][8];
    dragged = new JLabel();
    layers = getLayeredPane();
    mouseHandler = new MouseInputAdapter() {

 public void mouseReleased(MouseEvent mouseevent) {

            JLabel jlabel = (JLabel)mouseevent.getSource();
            Point point = jlabel.getLocation();
            Point point1 = mouseevent.getPoint();

            point.translate(point1.x, point1.y);
            Component component = boardPane.getComponentAt(point);
            JLabel jlabel1 = jlabel;

            if(hasIcon(component))
                    if(allowedMove(jlabel, component, k))
                            jlabel1 =(JLabel)component;
                    else
                        try{
                            if(bicie(jlabel,component,k))
                                jlabel1 =(JLabel)component;
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
            jlabel1.setIcon(dragged.getIcon());
            dragged.setVisible(false);

        }
 };

   boolean jump(JLabel jlabel, Component component)  {
      int x = jlabel.getX();
      int y = jlabel.getY();
      int x2=  component.getX();
      int y2=  component.getY();
      String h="";

      if(ballPressed=="redIcon" && player==true && y-y2==138 && x2-x==138){
          Point point = new Point(x+69, y-69);
          JLabel l=  (JLabel) jlabel.getComponentAt(point);
          try{
          q=l.getIcon();
          h = q.toString();

            if(h=="greenIcon"){
                player = false;
                message.setText("Green");
                getComponentAt(x2+69, y2+69).setBounds(0,0,0,0);
                ((JLabel) q).setIcon(null);
              return true;

          }
      }else

    return false;
}

对于跳转,我提供了一小部分代码(仅适用于正确的redIcon),因为我想要可读。

换行             q=l.getIcon();我得到java.lang.NullPointerException

http://s2.postimg.org/ywdxs56qx/exception.jpg

1 个答案:

答案 0 :(得分:0)

如果q=l.getIcon()给出空指针,那么l几乎肯定是空的。您从JLabel.getComponentAt()派生出l,并进行一些计算;如果“组件不包含位置”,则getComponentAt返回null。