import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.*;

public class BoutonSourieCadre extends JFrame{
    int x = 0;
    int y = 0;

    int vx = 1;
    int vy = 1;

    Timer timer;
    Bouton bouton;

    public BoutonSourieCadre() {

	// operation de fermeture
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
	// extraire les dimensions
	Toolkit kit=Toolkit.getDefaultToolkit();
	Dimension screenSize = kit.getScreenSize();

	// centrer l'image
	setSize(screenSize.width/2,screenSize.height/2);
	setLocation(screenSize.width/4,screenSize.height/4);
    
    // definir l'icone
	setTitle("Un titre");

    // ajouter le panneau au cadre
	add(new Panneau());

	// ajouter un timer
	timer = new Timer(100,new BougeAction());
	timer.start();

	// ajouter le bouton stop
	bouton = new Bouton();
	add(bouton,BorderLayout.NORTH);

	setVisible(true);
    }

    class Panneau extends JPanel
    {
	public Panneau()
	{
	    setBackground(Color.white);
	    setFocusable(true);
	    addKeyListener(new EcouteClavier());
	    addMouseListener(new EcouteSourie());
	}
		
	public void paintComponent(Graphics g){
	    super.paintComponent(g);

	    Graphics2D g2=(Graphics2D) g;

	    Rectangle2D rec = new Rectangle2D.Double(x,y,20,20);
	    g2.fill(rec);
	}
    }
	
    public class BougeAction implements ActionListener {
	public void actionPerformed(ActionEvent e) {
	    x += vx;
	    x = x % getWidth();
	    y += vy;
	    y = y %getHeight();
	    repaint();
	}
    }

    public class Bouton extends JButton {
	public Bouton() {
	    super("Stop");
	    addActionListener(new Stop());
	}
    }
    
    public class Stop implements ActionListener {
	public void actionPerformed(ActionEvent e) {
	    if (timer.isRunning()) {
		timer.stop();
		bouton.setText("Start");
	    }
	    else {
		timer.start();
		bouton.setText("Stop");
	    }
	}
    }

    class EcouteSourie implements MouseListener {
	public void mouseClicked(MouseEvent e) {
	}
	public void mouseEntered(MouseEvent e) {
	}
	public void mouseExited(MouseEvent e) {
	}
	public void mousePressed(MouseEvent e) {
	    x = e.getX();
	    y = e.getY();
	}
	public void mouseReleased(MouseEvent e) {
	}
    }

    class EcouteClavier implements KeyListener {
	public void keyPressed(KeyEvent e) {
	    int key = e.getKeyCode();
	    if (key == KeyEvent.VK_RIGHT) {
		vx += (vx>=0)?1:-1;
		vy += (vy>=0)?1:-1;
	    }
	    else if (key == KeyEvent.VK_LEFT) {
		if (vx!=0)
		    vx -= (vx>=0)?1:-1;
		if (vy!=0)
		    vy -= (vy>=0)?1:-1;
	    }		
	}
	public void keyReleased(KeyEvent e) {
	}
	public void keyTyped(KeyEvent e) {
	}
    }




    public static void main(String[] args){
	BoutonSourieCadre cadre = new BoutonSourieCadre();
    }
}
