package swingExamples;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.Timer;
class SimpleAnimationDisplayPanel extends JPanel
implements ActionListener
{
public SimpleAnimationDisplayPanel()
{
setBackground(Color.BLACK);
// This timer "goes off" every 10 milliseconds
Timer timer = new Timer(10, this);
timer.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setXORMode( getBackground() );
g.setColor(Color.RED);
g.fillRect(m_squareX, m_squareY, m_squareSize, m_squareSize);
g.setColor(Color.GREEN);
g.fillOval(m_ballX + m_ballDiameter / 2, m_ballY + m_ballDiameter / 2,
m_ballDiameter, m_ballDiameter);
}
public void actionPerformed(ActionEvent event)
{
// Do the animation by using XOR mode and repeated
// repaints, modifying the coordinates of the shapes
// between repaints.
int width = getWidth();
repaint();
m_ballX++;
if (m_ballX > width)
m_ballX = 0;
m_ballY++;
if (m_ballY > width)
m_ballY = 0;
m_squareX--;
if (m_squareX < 0)
m_squareX = width;
m_squareY++;
if (m_squareY > width)
m_squareY = 0;
repaint();
}
///// Private data /////
// Coordinates of the ball and square to animate.
private int m_ballX = 0;
private int m_ballY = 0;
private int m_ballDiameter = 30;
private int m_squareX = 200;
private int m_squareY = 0;
private int m_squareSize = 50;
}
public class SimpleAnimationDisplayApplet extends JApplet
{
public SimpleAnimationDisplayApplet()
{
Container contentPane = getContentPane();
contentPane.add(new SimpleAnimationDisplayPanel());
}
}
|