绘图和框架上的JLabel

时间:2015-03-15 22:58:14

标签: java swing nullpointerexception jlabel

我想用Java Frame创建一个Caterpillar游戏。它基本上有两个玩家试图占据一个正方形以增加他们的分数。我一直在使用两个班级:

毛毛虫课程

package caterpillar;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

class Caterpillar {

    private Color color;
    private Point position;
    private char direction;
    private Queue<Point> body;
    private Queue<Character> commands;
    private int score;

    public Caterpillar (Color c, Point p){
        color = c;
        direction = 'E';
        body = new LinkedList<Point>();
        score = 0;
        commands = new LinkedList<Character>();
        for (int i = 0; i < 10; i++){
            position= new Point(p.x + i, p.y);
            body.offer(position);
        }   
    }

    public void setDirection(char direction){
        commands.offer(new Character(direction));
    }

    public void move(CaterpillarGame game){
        if(commands.size()>0){
            Character c = (Character)commands.peek();
            commands.poll();
            direction = c.charValue();
            if(direction == 'Z') 
                return;
        }

        Point np = newPosition();
        if(game.canMove(np)){
            body.poll();
            body.offer(np);
            position = np;
        }
        score+=game.squareScore(np);    
    }

    private Point newPosition(){
        int x = position.x;
        int y = position.y;
        if(direction == 'E') 
            x++;
        else if(direction == 'W') 
            x--;
        else if(direction == 'N') 
            y--;
        else if(direction == 'S') 
            y++;
        return new Point(x, y);
    }

    public boolean inPosition(Point np){ //check if position has alredy been occupied
        Iterator <Point>it = body.iterator();
        while(it.hasNext()){
            Point location = it.next();
            if(np.equals(location)) 
                return true;
        }
        return false;
    }

    public int getScore(){
        return score;
    }

    public void paint(Graphics g){
        g.setColor(color);
        Iterator <Point>it = body.iterator();
        while(it.hasNext()){
            Point p = it.next();
            g.fillOval(5 + CaterpillarGame.SegmentSize * p.x,
                    15 + CaterpillarGame.SegmentSize * p.y,
                    CaterpillarGame.SegmentSize,
                    CaterpillarGame.SegmentSize);
        }
    }

}

游戏类:

package caterpillar;

import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;
import javax.swing.JLabel;

public class CaterpillarGame extends Frame{

final static int BoardWidth = 60;
final static int BoardHeight = 40;
final static int SegmentSize = 10;
private Caterpillar playerOne;
private Caterpillar playerTwo;
private Point square;
private int number; //points the players will get if occupy the square
private Random generator;
private JLabel score1, score2;// scores of two players

public static void main(String[] args){
    CaterpillarGame game= new CaterpillarGame();
    game.run();
}

public CaterpillarGame(){
    setBackground(Color.GREEN);
    setVisible(true);
    setSize((BoardWidth+1)*SegmentSize, BoardHeight*SegmentSize + 30);
    addKeyListener(new KeyReader());
    playerOne = new Caterpillar(Color.blue, new Point(20, 10));
    playerTwo = new Caterpillar(Color.red, new Point(20, 30));
    addWindowListener(new CloseQuit());
    generator = new Random();
    number = 1;
    score1 = new JLabel("Player One: "+playerOne.getScore());
    score2 = new JLabel("Player Two: "+playerTwo.getScore());
    this.add(score1);
    this.add(score2);
    square = new Point(newSquare());    
}

public void run(){
    while(true){
        movePieces();
        repaint();
        try{
            Thread.sleep(100);
        }catch(Exception e){}
    }
}

public void paint(Graphics g){
    playerOne.paint(g);
    playerTwo.paint(g);
    g.setColor(Color.white);
    g.fillRect(square.x, square.y, 10,10); //line 62, exception thrown
    g.setColor(Color.BLACK);
    g.drawString(Integer.toString(number), 10, 10);
}

public void movePieces(){
    playerOne.move(this);
    playerTwo.move(this);
}

public boolean canMove(Point np){
    int x = np.x;
    int y = np.y;
    if((x<=0)||(y<=0))
        return false;
    if((x>=BoardWidth)||(y>=BoardHeight))
        return false;
    if(playerOne.inPosition(np))
        return false;
    if(playerTwo.inPosition(np))
        return false;
    return true;
}

private class KeyReader extends KeyAdapter{
    public void keyPressed(KeyEvent e){
        char c = e.getKeyChar();
        switch(c){
        case 'q': playerOne.setDirection('Z'); 
                  break;
        case 'a': playerOne.setDirection('W');
                  break;
        case 'd': playerOne.setDirection('E');
                  break;
        case 'w': playerOne.setDirection('N');
                  break;
        case 's': playerOne.setDirection('S');
                  break;
        case 'p': playerTwo.setDirection('Z');
                  break;
        case 'j': playerTwo.setDirection('W');
                  break;
        case 'l': playerTwo.setDirection('E');
                  break;
        case 'i': playerTwo.setDirection('N');
                  break;
        case 'k': playerTwo.setDirection('S');
                  break;
        }
    }
}

public Point newSquare(){
    Point p = new Point(generator.nextInt(51), generator.nextInt(31));
    while(playerOne.inPosition(p)||playerTwo.inPosition(p)){
        p = new Point(generator.nextInt(51), generator.nextInt(31));
    }
    number++;
    return square = p;
}

public int squareScore(Point p){
    if(p.equals(square)){
        newSquare();
        return number;
    }
    return 0;
}

private class CloseQuit extends WindowAdapter{
    public void windowClosing(WindowEvent e){
        System.exit(0);
    }
}

}

这是我到目前为止所做的,但是当我运行程序时我遇到了几个问题:

  1. JLabels,square和string没有显示
  2. 它不断抛出java.lang.NullPointerException the exception occurs at line 62
  3. 当一名玩家的分数达到一定数量时,如何停止该程序?
  4. 如何检查毛毛虫是否接触广场?
  5. 提前致谢。

1 个答案:

答案 0 :(得分:1)

  

JLabels,square和string没有显示

他们是,你只是如此严重地搞砸油漆过程,以至于你不能对它们进行涂漆。而且,我相信&#34; java.awt.Frame使用BorderLayout

这是我们通常不鼓励人们压倒paint的原因之一,它很容易打破油漆链

在执行任何自定义绘画之前,请先调用super.paint

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

我更倾向于您使用基于paintComponent的类中的JComponent并将该对象添加到您的框架中,但您似乎有这样做的限制......

此外,将布局管理器更改为FlowLayout,以在屏幕上显示两个标签。

有关详细信息,请参阅Painting in AWT and SwingLaying Out Components Within a Container

  

它不断抛出java.lang.NullPointerException

这似乎是竞争条件。基本上,在您完成初始化UI要求之前,您正在框架上调用setVisible,这导致在框架完全初始化之前调用paint

最后致电setVisible。更好的是,不要在构造函数中调用setVisible ...

  

当一个玩家的得分达到一定数量时,如何让程序停止?

...在你的&#34;游戏循环中#34;你需要检查分数的状态并打破游戏循环&#34;当所需的状态满足时......

  

如何检查毛毛虫是否接触到正方形?

这是一个更复杂的问题。基本上,您可以使用interests(或其他contains对象的RectangleShape方法。您知道Point和&#34;段&#34;的square位置。的Caterpillar是。您知道square和&#34;段&#34;。

的大小

您需要比较每个细分,看它们是否与square的are相交。仔细查看java.awt.Rectangle了解更多详情