java - 在框架上绘图和 JLabel

标签 java swing nullpointerexception jlabel

我想使用 Java Frame 创建一个毛毛虫游戏。它基本上有两个玩家试图占据一个方格来增加他们的分数。我一直在使用两个类:

毛毛虫类

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、方 block 和字符串未显示
  2. 它一直抛出 java.lang.NullPointerException the exception occurs at line 62
  3. 当一名玩家的分数达到一定数量时,如何停止程序?
  4. 如何检查毛毛虫是否接触到了正方形?

提前致谢。

最佳答案

the JLabels, square, and string didn't show up

他们是的,你只是把油漆过程搞砸了,以至于你阻止了他们被油漆。另外,我“相信”java.awt.Frame 使用 BorderLayout

这是我们通常不鼓励人们重写paint的原因之一,打破绘画链非常容易

在执行任何自定义绘画之前添加对 super.paint 的调用。

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

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

此外,将布局管理器更改为 FlowLayout 之类的内容,以使两个标签都显示在屏幕上。

参见Painting in AWT and SwingLaying Out Components Within a Container了解更多详情

it kept throwing java.lang.NullPointerException

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

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

how do i have the program stopped when the score of one player reaches a certain number?

...在您的“游戏循环”中,您需要检查分数的状态,并在满足所需状态时打破“游戏循环”...

how to check if a caterpillar touches the square?

这是一个更复杂的问题。本质上,您可以使用 Rectangle (或其他 Shape 对象)的 interestscontains 方法。您知道正方形毛毛虫 的“线段”在哪里。您知道正方形和“线段”的大小。

您需要比较每个线段,看看它们是否与正方形相交。仔细看看java.awt.Rectangle了解更多详情

关于java - 在框架上绘图和 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29067228/

相关文章:

java - 使用 Spark 将字段添加到 Csv

java - 即使我单击“否”按钮,程序总是重复

java - 我应该使用什么组件在 Java 中绘制树状图?

android - android 中的自定义对话框?

java - 如何安全存储SecretKey?

java - 如何解决 "WebSphere API classes are not available"?

java - 在 Java 中生成 Web 服务客户端的简单方法,无需使用 Axis

java - JCEF - Java 运行时环境检测到 fatal error

android - ViewFlipper导致空指针异常

java - Mockito 上的 Nullpointer 何时