JPanels没有露面,有点儿

时间:2016-12-20 03:11:26

标签: java jframe jpanel synchronized

我是一名在校学生的业余爱好者在java中制作蛇游戏,它不完整,我遇到了一个我似乎无法修复的问题。吃完目标后,身体的第一和第二部分显得很好,但之后它们没有。

添加正文部分的代码:

  public void addBody(int x, int y) {
    snekBody.add(new JPanel());
    snekBody.get(snekBody.size() - 1).setBackground(new Color(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
    snekBody.get(snekBody.size() - 1).setVisible(true);
    snekBody.get(snekBody.size() - 1).setBounds(x*score, y*score, BODY_WIDTH, BODY_HEIGHT);
    game.add(snekBody.get(this.snekBody.size() - 1));
    revalidate();
  }
}

移动身体部位的代码(moveUp,moveDown等:

public synchronized void moveRight(int x, int y) {
    timer++;
    while (!this.right) {
      try {
        wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    head.setBounds(x, y, 20, 20);
    xCoords.add(x);
    yCoords.add(y);
    //snekBody is an ArrayList of type JPanel
    for(int i = 0; i < snekBody.size(); i++) {
      if (i > 0) {
        snekBody.get(i).setBounds(xCoords.get(timer-(10*score)), yCoords.get(timer-(10*score))+5, BODY_WIDTH, BODY_HEIGHT);
      } else {
        snekBody.get(i).setBounds(xCoords.get(timer-10), yCoords.get(timer-10)+5, BODY_WIDTH, BODY_HEIGHT);
      }
    }
    repaint();
    notifyAll();
    revalidate();
  }

调用addBody的代码:

 if (snek.up) {
          snek.addBody(snek.xCoords.get(snek.timer-20), snek.yCoords.get(snek.timer-20));

the second picture is the snake when more than two targets have been eaten. the panels for the body just stop showing up. The first picture is the snake when two targets have been eaten

1 个答案:

答案 0 :(得分:0)

事实证明,面板彼此重叠,因此我无法看到它们。