
import javax.swing.*;


/**
 *
 * 
 */
public class MischievousMain {
    public static void main(String[] args) {
       JFrame frame = new JFrame("Bouncing Cube");
       frame.setSize(500, 500);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       // mischievous square input
       frame.add(new BouncingMischievousSquare());
       frame.setVisible(true);
    }  
    
    
    
/**
 *
 * 
 */
import java.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class BouncingMischievousSquare extends JPanel implements ActionListener { 
    
    private static final int SQUARE_SIZE = 40;
    private static final int SPEED_OF_SQUARE = 6;
    private int xPosit, yPosit;
    private int xSpeed, ySpeed;
    
    BouncingMischievousSquare(){
        //speed  direction
        xSpeed = SPEED_OF_SQUARE;
        ySpeed = -SPEED_OF_SQUARE;
        //a timer for repaint 
        //http://d...content-available-to-author-only...e.com/javase/tutorial/uiswing/misc/timer.html
        Timer timer = new Timer(100, this);
        timer.start();
    }
    public void actionPerformed(ActionEvent e){
        //Screensize
        int width = getWidth();
        int height = getHeight();
        xPosit += xSpeed;
        yPosit += ySpeed;
        //test xAxis
        if(xPosit < 0){
            xPosit = 0;
            xSpeed = SPEED_OF_SQUARE;
        }
        else if(xPosit > width - SQUARE_SIZE){ 
            xPosit = width - SQUARE_SIZE;
            xSpeed = -SPEED_OF_SQUARE;
        }
        if(yPosit < 0){
            yPosit = 0;
            ySpeed = SPEED_OF_SQUARE;
        }
           else if(yPosit > height - SQUARE_SIZE){ 
            xPosit = height - SQUARE_SIZE;
            xSpeed = -SPEED_OF_SQUARE;
           }
        //ask the computer gods to redraw the square
        repaint();
    }
     public void paintComponent(Graphics g){       
         super.paintComponent(g);
         g.fillRect(xPosit, yPosit, SQUARE_SIZE, SQUARE_SIZE );
     }
}
     
     
     
