Tuesday, 1 September 2015

Designing the Animations- Java 7(Part 2)-The Code

Here is the code snippet for the Ball_Animate.java:
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
public class Animate_Ball {

    public static JFrame fr;
    public static JLabel ball1;
    public static Timer balltimer;
    public static Container c;
    public static ImageIcon i;
   
   
    public Animate_Ball() {
       
        fr=new JFrame();
        ball1=new JLabel();
        c=fr.getContentPane();
        i=new ImageIcon("ball.png");
       
        c.setLayout(null);
       
        fr.setBounds(0, 0, 800, 500);
       
        ball1.setBounds(0, 9, 179, 168);
       
        ball1.setIcon(i);
        c.setBackground(Color.black);
        c.add(ball1);
        fr.setVisible(true);
       
balltimer=new Timer(6, new ActionListener() {            //ball animator
           
            @Override
            public void actionPerformed(ActionEvent arg0) {
       
                if(ball1.getX()<fr.getWidth()){
                    ball1.setLocation(ball1.getX()+5,ball1.getY());
                }
                else{
                    ball1.setLocation(0,9);
                }
                   
            }
        });

    }
   
    public static void main(String arr[]){
        Animate_Ball n=new Animate_Ball();
        n.balltimer.start();
    }

}

And the output will be moving ball. You can experiment it with the moving ball vertically by changing the ball1.getY()+5.


Happy designing with java.

No comments: