Bouncing ball in a Swing window

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

public class BouncingBall {

  private static class BallPanel extends JPanel {

    // http://www.iconfinder.com/icondetails/8839/64/beach_ball_tourism_toys_icon
    private final Icon ball = new ImageIcon( BouncingBall.class.getResource( "ball.png" ) );
    private int ballX, ballY, dx = 2, dy = 2;

    public BallPanel() {
      new Timer( 10, new ActionListener() {
        @Override
        public void actionPerformed( ActionEvent evt ) {
          ballX += dx;
          ballY += dy;

          if ( ballX <= 0 || ballX + ball.getIconWidth() >= getWidth() )
            dx = -dx;
          if ( ballY <= 0 || ballY + ball.getIconHeight() >= getHeight() )
            dy = -dy;

          repaint();
        }
      } ).start();
    }

    @Override
    public void paint( Graphics g ) {
      Graphics2D g2d = (Graphics2D) g;
      g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
      g2d.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );

      g2d.setColor( Color.WHITE );
      g2d.fill( getBounds() );

      ball.paintIcon( null, g2d, ballX, ballY );
    }
  }

  public static void main( String[] args ) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    f.setIgnoreRepaint( true );
    f.add( new BallPanel() );
    f.setBounds( 200, 100, 400, 200 );
    f.setVisible( true );
  }
}

Ähnliche Beiträge

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert