Eclipse中的Java异常 [英] java exception in eclipse

查看:70
本文介绍了Eclipse中的Java异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我在Internet上的Java中找到了一些用于突围游戏的代码,我试图在Eclipse中运行它,但它会引发异常.

如果有人可以帮助我的话.

这是代码:
游戏包含七个文件.
Commons.java

Hi
I found some code for breakout game in java on internet, i tried to run it in eclipse, but it throws exceptions.

if anyone could please help me out.

here is the code:
The game consists of seven files.
Commons.java

package breakout;

public interface Commons {
    public static final int WIDTH = 300;
    public static final int HEIGTH = 400;
    public static final int BOTTOM = 390;
    public static final int PADDLE_RIGHT = 250;
    public static final int BALL_RIGHT = 280;
}


Commons.java文件具有一些公共常量.
Sprite.java


The Commons.java file has some common constants.
Sprite.java

package breakout;
import java.awt.Image;
import java.awt.Rectangle;

public class Sprite {

    protected int x;
    protected int y;
    protected int width;
    protected int heigth;
    protected Image image;


    public void setX(int x) {
        this.x = x;
    }

    public int getX() {
        return x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getY() {
        return y;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return heigth;
    }

    Image getImage()
    {
      return image;
    }

    Rectangle getRect()
    {
      return new Rectangle(x, y, 
          image.getWidth(null), image.getHeight(null));
    }
}


Sprite类是板上所有对象的基类.我们在这里放置Ball,Brick和Paddle对象中的所有方法和变量.类似于getImage()或getX()方法.
Brick.java


The Sprite class is a base class for all objects on the Board. We put here all methods and variables that are in Ball, Brick and Paddle objects. Like getImage() or getX() methods.
Brick.java

package breakout;
import javax.swing.ImageIcon;

public class Brick extends Sprite {

    String brickie = "../images/brickie.png";

    boolean destroyed;


    public Brick(int x, int y) {
      this.x = x;
      this.y = y;

      ImageIcon ii = new ImageIcon(this.getClass().getResource(brickie));
      image = ii.getImage();

      width = image.getWidth(null);
      heigth = image.getHeight(null);

      destroyed = false;
    }

    public boolean isDestroyed()
    {
      return destroyed;
    }

    public void setDestroyed(boolean destroyed)
    {
      this.destroyed = destroyed;
    }

}


这是Brick类.


This is the Brick class.

boolean destroyed;


在销毁的变量中,我们保留砖的状态.
Ball.java


In the destroyed variable we keep the state of a brick.
Ball.java

package breakout;
import javax.swing.ImageIcon;

public class Ball extends Sprite implements Commons {

   private int xdir;
   private int ydir;

   protected String ball = "../images/ball.png";

   public Ball() {

     xdir = 1;
     ydir = -1;

     ImageIcon ii = new ImageIcon(this.getClass().getResource(ball));
     image = ii.getImage();

     width = image.getWidth(null);
     heigth = image.getHeight(null);

     resetState();
    }


    public void move()
    {
      x += xdir;
      y += ydir;

      if (x == 0) {
        setXDir(1);
      }

      if (x == BALL_RIGHT) {
        setXDir(-1);
      }

      if (y == 0) {
        setYDir(1);
      }
    }

    public void resetState() 
    {
      x = 230;
      y = 355;
    }

    public void setXDir(int x)
    {
      xdir = x;
    }

    public void setYDir(int y)
    {
      ydir = y;
    }

    public int getYDir()
    {
      return ydir;
    }
}


这是Ball类.


This is the Ball class.

public void move()
{
  x += xdir;
  y += ydir;

  if (x == 0) {
    setXDir(1);
  }

  if (x == BALL_RIGHT) {
    setXDir(-1);
  }

  if (y == 0) {
    setYDir(1);
  }
}


move()方法将球移到棋盘上.如果球撞到边界,则方向也会相应更改.


The move() method moves the ball on the Board. If the ball hits the borders, the directions are changed accordingly.

public void setXDir(int x)
{
  xdir = x;
}
public void setYDir(int y)
{
  ydir = y;
}


当球击中桨或砖时,将调用这两种方法.
Paddle.java


These two methods are called, when the ball hits the paddle or a brick.
Paddle.java

package breakout;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;

public class Paddle extends Sprite implements Commons {

    String paddle = "../images/paddle.png";

    int dx;

    public Paddle() {

        ImageIcon ii = new ImageIcon(this.getClass().getResource(paddle));
        image = ii.getImage();

        width = image.getWidth(null);
        heigth = image.getHeight(null);

        resetState();

    }

    public void move() {
        x += dx;
        if (x <= 2) 
          x = 2;
        if (x >= Commons.PADDLE_RIGHT)
          x = Commons.PADDLE_RIGHT;
    }

    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        if (key == KeyEvent.VK_LEFT) {
            dx = -2;

        }

        if (key == KeyEvent.VK_RIGHT) {
            dx = 2;
        }
    }

    public void keyReleased(KeyEvent e) {
        int key = e.getKeyCode();

        if (key == KeyEvent.VK_LEFT) {
            dx = 0;
        }

        if (key == KeyEvent.VK_RIGHT) {
            dx = 0;
        }
    }

    public void resetState() {
        x = 200;
        y = 360;
    }
}


这是Paddle类.它封装了Breakout游戏中的paddle对象.操纵杆通过左右箭头键控制.通过按箭头键,我们设置方向变量.通过释放箭头键,我们将dx变量设置为零.这样桨停止运动.
Board.java


This is the Paddle class. It encapsulates the paddle object in the Breakout game. The paddle is controlled with left and right arrow keys. By pressing the arrow key, we set the direction variable. By releasing the arrow key, we set the dx variable to zero. This way the paddle stops moving.
Board.java

package breakout;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JPanel;

public class Board extends JPanel implements Commons {

    Image ii;
    Timer timer;
    String message = "Game Over";
    Ball ball;
    Paddle paddle;
    Brick bricks[];

    boolean ingame = true;
    int timerId;

    public Board() {

        addKeyListener(new TAdapter());
        setFocusable(true);

        bricks = new Brick[30];
        setDoubleBuffered(true);
        timer = new Timer();
        timer.scheduleAtFixedRate(new ScheduleTask(), 1000, 10);
    }

        public void addNotify() {
            super.addNotify();
            gameInit();
        }

    public void gameInit() {

        ball = new Ball();
        paddle = new Paddle();

        int k = 0;
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 6; j++) {
                bricks[k] = new Brick(j * 40 + 30, i * 10 + 50);
                k++;
            }
        }
    }

    public void paint(Graphics g) {
        super.paint(g);

        if (ingame) {
            g.drawImage(ball.getImage(), ball.getX(), ball.getY(),
                        ball.getWidth(), ball.getHeight(), this);
            g.drawImage(paddle.getImage(), paddle.getX(), paddle.getY(),
                        paddle.getWidth(), paddle.getHeight(), this);

            for (int i = 0; i < 30; i++) {
                if (!bricks[i].isDestroyed())
                    g.drawImage(bricks[i].getImage(), bricks[i].getX(),
                                bricks[i].getY(), bricks[i].getWidth(),
                                bricks[i].getHeight(), this);
            }
        } else {

            Font font = new Font("Verdana", Font.BOLD, 18);
            FontMetrics metr = this.getFontMetrics(font);

            g.setColor(Color.BLACK);
            g.setFont(font);
            g.drawString(message,
                         (Commons.WIDTH - metr.stringWidth(message)) / 2,
                         Commons.WIDTH / 2);
        }


        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }

    private class TAdapter extends KeyAdapter {

        public void keyReleased(KeyEvent e) {
            paddle.keyReleased(e);
        }

        public void keyPressed(KeyEvent e) {
            paddle.keyPressed(e);
        }
    }

    class ScheduleTask extends TimerTask {
        public void run() {
            ball.move();
            paddle.move();
            checkCollision();
            repaint();
        }
    }

    public void stopGame() {
        ingame = false;
        timer.cancel();
    }

    public void checkCollision() {
        if (ball.getRect().getMaxY() > Commons.BOTTOM) {
            stopGame();
        }

        for (int i = 0, j = 0; i < 30; i++) {
            if (bricks[i].isDestroyed()) {
                j++;
            }
            if (j == 30) {
                message = "Victory";
                stopGame();
            }
        }

        if ((ball.getRect()).intersects(paddle.getRect())) {

            int paddleLPos = (int)paddle.getRect().getMinX();
            int ballLPos = (int)ball.getRect().getMinX();

            int first = paddleLPos + 8;
            int second = paddleLPos + 16;
            int third = paddleLPos + 24;
            int fourth = paddleLPos + 32;

            if (ballLPos < first) {
                ball.setXDir(-1);
                ball.setYDir(-1);
            }

            if (ballLPos >= first && ballLPos < second) {
                ball.setXDir(-1);
                ball.setYDir(-1 * ball.getYDir());
            }

            if (ballLPos >= second && ballLPos < third) {
                ball.setXDir(0);
                ball.setYDir(-1);
            }

            if (ballLPos >= third && ballLPos < fourth) {
                ball.setXDir(1);
                ball.setYDir(-1 * ball.getYDir());
            }

            if (ballLPos > fourth) {
                ball.setXDir(1);
                ball.setYDir(-1);
            }
        }

        for (int i = 0; i < 30; i++) {
            if ((ball.getRect()).intersects(bricks[i].getRect())) {

                int ballLeft = (int)ball.getRect().getMinX();
                int ballHeight = (int)ball.getRect().getHeight();
                int ballWidth = (int)ball.getRect().getWidth();
                int ballTop = (int)ball.getRect().getMinY();

                Point pointRight =
                    new Point(ballLeft + ballWidth + 1, ballTop);
                Point pointLeft = new Point(ballLeft - 1, ballTop);
                Point pointTop = new Point(ballLeft, ballTop - 1);
                Point pointBottom =
                    new Point(ballLeft, ballTop + ballHeight + 1);

                if (!bricks[i].isDestroyed()) {
                    if (bricks[i].getRect().contains(pointRight)) {
                        ball.setXDir(-1);
                    }

                    else if (bricks[i].getRect().contains(pointLeft)) {
                        ball.setXDir(1);
                    }

                    if (bricks[i].getRect().contains(pointTop)) {
                        ball.setYDir(1);
                    }

                    else if (bricks[i].getRect().contains(pointBottom)) {
                        ball.setYDir(-1);
                    }

                    bricks[i].setDestroyed(true);
                }
            }
        }
    }
}


这是董事会类.这里我们把游戏逻辑.


This is the Board class. Here we put the game logic.

public void gameInit() {

    ball = new Ball();
    paddle = new Paddle();

    int k = 0;
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 6; j++) {
            bricks[k] = new Brick(j * 40 + 30, i * 10 + 50);
            k++;
        }
    }
}


在gameInit()方法中,我们创建了一个球,一个球拍和30个积木.


In the gameInit() method we create a ball a paddle and 30 bricks.

if (ingame) {
     g.drawImage(ball.getImage(), ball.getX(), ball.getY(),
                 ball.getWidth(), ball.getHeight(), this);
     g.drawImage(paddle.getImage(), paddle.getX(), paddle.getY(),
                 paddle.getWidth(), paddle.getHeight(), this);

     for (int i = 0; i < 30; i++) {
         if (!bricks[i].isDestroyed())
             g.drawImage(bricks[i].getImage(), bricks[i].getX(),
                         bricks[i].getY(), bricks[i].getWidth(),
                         bricks[i].getHeight(), this);
     }
 }


如果游戏未完成,我们将在绘画事件中绘制球,桨和砖块.


If the game is not finished, we draw the ball, the paddle and the bricks inside the paint event.

class ScheduleTask extends TimerTask {

    public void run() {
        ball.move();
        paddle.move();
        checkCollision();
        repaint();
    }
}


ScheduleTask每10毫秒触发一次.在run方法中,我们移动球和球拍.我们检查是否可能发生碰撞.然后我们重新粉刷屏幕.


The ScheduleTask is triggerd every 10 ms. In the run method, we move the ball and the paddle. We check for possible collisiont. And we repaint the screen.

if (ball.getRect().getMaxY() > Commons.BOTTOM)
       stopGame();
}


如果球撞到底部,我们将停止比赛.


If the ball hits the bottom, we stop the game.

for (int i = 0, j = 0; i < 30; i++) {
    if (bricks[i].isDestroyed()) {
        j++;
    }
    if (j == 30) {
        message = "Victory";
        stopGame();
    }
}


我们检查了多少砖被破坏了.如果我们摧毁了所有30块积木,我们将赢得比赛.


We check how many bricks are destroyed. If we destroyed all 30 bricks, we win the game.

if (ballLPos < first) {
    ball.setXDir(-1);
    ball.setYDir(-1);
}


如果球碰到了桨的第一部分,我们会将球的方向更改为东北.


If the ball hits the first part of the paddle, we change the direction of the ball to the north-east.

if (bricks[i].getRect().contains(pointTop)) {
    ball.setYDir(1);
}


如果球撞击砖的底部,我们将改变球的y方向.它下降了.

每个游戏周期都会调用autoMove()方法以在屏幕上移动球.如果碰到边界,球的方向就会改变.

Breakout.java


If the ball hits the bottom of the brick, we change the y direction of the ball. It goes down.

The autoMove() method is called each game cycle to move the ball on the screen. If it hists the boundaries, the ball direction changes.

Breakout.java

package breakout;
import javax.swing.JFrame;

public class Breakout extends JFrame {

    public Breakout()
    {
        add(new Board());
        setTitle("Breakout");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(Commons.WIDTH, Commons.HEIGTH);
        setLocationRelativeTo(null);
        setIgnoreRepaint(true);
        setResizable(false);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Breakout();
    }
}


这是例外:


here are the exceptions:

Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(Unknown Source)
    at Ball.<init>(Ball.java:14)
    at Board.gameInit(Board.java:48)
    at Board.addNotify(Board.java:43)
    at java.awt.Container.addNotify(Unknown Source)
    at javax.swing.JComponent.addNotify(Unknown Source)
    at java.awt.Container.addNotify(Unknown Source)
    at javax.swing.JComponent.addNotify(Unknown Source)
    at java.awt.Container.addNotify(Unknown Source)
    at javax.swing.JComponent.addNotify(Unknown Source)
    at javax.swing.JRootPane.addNotify(Unknown Source)
    at java.awt.Container.addNotify(Unknown Source)
    at java.awt.Window.addNotify(Unknown Source)
    at java.awt.Frame.addNotify(Unknown Source)
    at java.awt.Window.show(Unknown Source)
    at java.awt.Component.show(Unknown Source)
    at java.awt.Component.setVisible(Unknown Source)
    at java.awt.Window.setVisible(Unknown Source)
    at BrickBreaker.<init>(BrickBreaker.java:16)
    at BrickBreaker.main(BrickBreaker.java:20)
Exception in thread "Timer-0" java.lang.NullPointerException
    at Board$ScheduleTask.run(Board.java:110)
    at java.util.TimerThread.mainLoop(Unknown Source)
    at java.util.TimerThread.run(Unknown Source)

推荐答案

ScheduleTask.run(Board.java:110) 在java.util.TimerThread.mainLoop处(未知源) 在java.util.TimerThread.run(未知来源)
ScheduleTask.run(Board.java:110) at java.util.TimerThread.mainLoop(Unknown Source) at java.util.TimerThread.run(Unknown Source)


Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(Unknown Source)
    at Ball.<init>(Ball.java:14)
    at Board.gameInit(Board.java:48)
</init></init>



您应该学习阅读该异常-它全部都写在这里:
ImageIcon上有一个空指针.在第14行的Ball类中抛出了空指针.

请在Eclipse首选项中打开行号(在窗口->首选项->中输入文本编辑器",然后参考选项窗格).

您也可以在此类异常上放置一个断点,只需在控制台视图中单击该异常并接受对话框即可.然后,您应该能够在视图"Breakpoints"(调试布局)中将异常视为断点(调试布局,我想将该视图添加到我的普通" Java视图中(窗口"->显示视图"->其他"->调试)).
然后,当您调试该代码时,调试器将在nullpointer处停止.然后,您可以在调试视图中检查堆栈,并查看代码失败的地方.



You should learn to read the exception - it''s all written there:
There is a nullpointer on the ImageIcon. The nullpointer is thrown in the class Ball on line 14.

Please switch on line numbers in the Eclipse Preferences (Window -> Preferences-> enter "text editor" and refer to the option pane).

You can also place a break point on such exceptions, just click on the exception in the console view and accept the dialog. You should then be able to see the exception as a break point in the view "Breakpoints" (Debug layout, I like to add that view to my "normal" Java view (Window->show View -> other -> debug)).
Then, when you debug that code, the debugger will stop at the nullpointer. You can then check the stack in the debug view and see where your code failed.


这篇关于Eclipse中的Java异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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