0

JFrame私は Java の学習を始めたばかりで、とを除いて GUI コンポーネントについてあまり知りませんJLayout

オブジェクト (ボール) を JFrame に実装し、壁を無限に跳ね返らせるにはどうすればよいですか?

4

2 に答える 2

0

1 つの方法は、オーバーライドされた paintComponent メソッドを持つ JPanel のサブクラスを 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);
   }
}
于 2013-04-13T12:29:50.240 に答える