---
title: 'Bouncing ball in a Swing window'
url: 'https://tutego.de/blog/javainsel/2016/03/bouncing-ball-in-a-swing-window'
markdown: 'https://tutego.de/blog/javainsel/2016/03/bouncing-ball-in-a-swing-window.md'
date: '2016-03-10'
description: '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.getRes…'
taxonomy:
  category:
    - Allgemein
---

# Bouncing ball in a Swing window

![Illustration einer tropischen Insel mit Palmen und einem hohen Berg](https://tutego.de/blog/javainsel/user/themes/tutego/images/insel-cover.jpg)# Java Blog für Programmierer

[Java Blog für Programmierer](https://tutego.de/blog/javainsel/)

## Bouncing ball in a Swing window

10.03.2016 · [Christian Ullenboom](https://tutego.de/blog/javainsel/author/admin/)

 ```java
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 = getWidth() )
            dx = -dx;
          if ( ballY = 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 );
  }
}
```

Kategorien: [Allgemein](https://tutego.de/blog/javainsel/category/allgemein/)

[← Alle Beiträge](https://tutego.de/blog/javainsel/)

---

## Navigation

- Previous: [Retrieve Windows netstat data and observe new network connections](https://tutego.de/blog/javainsel/2016/03/retrieve-windows-netstat-data-and-observe-new-network-connections.md)
