我正在尝试创建一个“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();
}
}
最佳答案
尝试这样的事情
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());
}
关于java - 如何添加更多球并使它们具有不同的起始位置?以我的方法来说这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19433916/