Java Animation

Discussion in 'Java' started by Alioune, Aug 4, 2017.

  1. Alioune

    Alioune

    Joined:
    Jul 19, 2017
    Messages:
    13
    Likes Received:
    2
    Location:
    Phoenix, AZ
    I am trying to create a bouncing animation similar to this one:

    [​IMG]

    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?
     
    Alioune, Aug 4, 2017
    #1
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.