3

我试图创建一个“bouncingBall”屏幕保护程序类型的程序。而且我很难编程更多的球/椭圆,并使它们有一个随机的起点。如果可能并且不会太复杂,我想保持我对这个问题的处理方式不变。我的第一个问题,我是编程新手,如果这种方式完全错误,请告诉我。谢谢你的回答。

public class Game {

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

public class Spillvindu extends JFrame {

  private Anothergame game;

  Spillvindu() {
    add(game = new Anothergame());
    game.lagSpillVindu();
    pack();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setVisible(true);
  }

  public Dimension getPreferredSize() {
    return new Dimension(800, 600);
  }
}

public class Anothergame extends JComponent implements ActionListener {

  void lagSpillVindu() {
    Timer t = new Timer(10, this);
    t.start();
  }
  private int ballYSpeed = 5;

  private int ballXSpeed = 5;

  private int ballX;

  private int ballY;

  private static Random random = new Random(800);

  public void paintComponent(Graphics g) {
    g.setColor(Color.CYAN);
    g.fillRect(0, 0, 800, 600);
    g.setColor(Color.black);
    g.fillOval(ballX, ballY, 40, 40);
  }

  public void actionPerformed(ActionEvent arg0) {
    ballX = ballX + ballXSpeed;
    ballY = ballY + ballYSpeed;
    if (ballY >= 520) {
      ballYSpeed = - 5;
    }
    if (ballX >= 730) {
      ballXSpeed = - 5;
    }
    if (ballX <= 0) {
      ballXSpeed = 5;
    }
    if (ballY <= 0) {
      ballYSpeed = 5;
    }
    repaint();
  }
}
4

1 回答 1

0

尝试这样的事情

class Ball {
  private int ballX;
  private int ballY;
  private int ballWidth;
  private int ballHeight;

  Ball(int x, int y, int width, int height) {
    ballX = x;
    ballY = y
    ballWidth = width;
    ballHeight = height;
  }
  // ... (add getter methods)
}

那么你会有类似的东西:

List<Ball> balls = getBalls(); // Create a bunch of balls somehow
// ...
for (Ball ball : balls) {
  // update the balls position
}

然后渲染它们:

public void paintComponent(Graphics g) {
  g.setColor(Color.CYAN);
  g.fillRect(0,0, 800, 600);
  g.setColor(Color.black)
  for (Ball b : balls)
    g.fillOval(b.getX(), b.getY(), b.getWidth(), b.getHeight());
}
于 2013-10-17T18:14:01.700 回答