Java Animation

Joined
Jul 19, 2017
Messages
13
Reaction score
2
I am trying to create a bouncing animation similar to this one:

8f8cb429-ddd8-47c7-9550-c1a8a366c03b


This is the code that I've written:

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


public class GraphicsPractice implements ActionListener
{

private static JFrame frame;
private static JPanel panel;
private static Timer timer;
private static ImageIcon image;
private static final int WIDTH = 300, HEIGHT = 100, IMAGE_SIZE = 35;
private static int x, y, moveX, moveY;
private static final int DELAY = 20;
private static Graphics g;


public static void main(String[] args)
{
frame = new JFrame("Traveling Head");
frame.setVisible(true);
frame.setLocation(300 , 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
timer = new Timer(DELAY, new GraphicsPractice());
image = new ImageIcon("Head.gif");
image.paintIcon(panel, g, x, y);

x = 0;
y = 40;
moveX = moveY = 3;

panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
panel.setBackground(Color.black);
timer.addActionListener(new GraphicsPractice());
timer.start();

frame.getContentPane().add(panel);
frame.pack();

}

public void actionPerformed(ActionEvent event)
{
x += moveX;
y += moveY;

if(x <= 0 || x >= WIDTH-IMAGE_SIZE)
{
moveX *= -1;
}

if(y <= 0 || y >= HEIGHT-IMAGE_SIZE)
{
moveY *= -1;
}

panel.repaint();
}

}

I'm having problems with the paintIcon method. How do I use this method?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top