我试图创建一个“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();
}
}