如何在JFrame中实现一个对象并使其反弹

时间:2013-04-13 10:31:11

标签: java user-interface

我刚开始学习java,除了JFrameJLayout之外,对GUI组件了解不多。

如何在JFrame中实现一个对象(球),让它无限次地反弹?

2 个答案:

答案 0 :(得分:0)

您可以使用swing概念

通过Thread创建它
  • 您可以在swing概念

  • 中通过swing drawImage创建球
  • 要执行移动和延迟概念,您可以使用Thread pakage

要执行此操作,请参阅参考Java complete edition 7

答案 1 :(得分:0)

一种方法是将JPanel的子类与重写的paintComponent方法添加到JFrame中。这个类可以有球位置的字段,javax.swing.Timer用于重新绘制面板。它可能是这样的(未经测试):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class BouncingBall extends JPanel{
    //Ball position
    private int x = 0;
    private int y = 0;
    //Position change after every repaint
    private int xIncrement = 5;
    private int yIncrement = 5;
    //Ball radius
    private final int R = 10;

    private Timer timer;

    public BouncingBall(){
        timer = new Timer(25, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               BouncingBall.this.repaint();
        }
         });

    timer.start();
   }

   @Override
   protected void paintComponent(Graphics g) {
       super.paintComponent(g);
       //If the ball hits one of the panel boundaries
       //change to the opposite direction
       if (x < 0 || x > getWidth()) {
           xIncrement *= -1;
       }
       if (y < 0 || y > getHeight()) {
           yIncrement *= -1;
       }
       //increment position
       x += xIncrement;
       y += yIncrement;
       //draw the ball
       g.fillOval(x - R, y - R, R * 2, R * 2);
   }
}