Wednesday, July 28, 2010

Move the line

playing with java Graphics2D and Line2D


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

public class ShapeTest extends JLabel implements MouseListener, MouseMotionListener
{
    Line2D line = new Line2D.Float(20,20,200,200);
   
    Line2D activeShape;
   
    boolean dragging;
   
    int startX,startY;
    int startShapeX,startShapeY;
    int endShapeX,endShapeY;
   
    public ShapeTest()
    {
        addMouseListener(this);
        addMouseMotionListener(this);
    }
   
   
    public void paint(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;
        g2.draw(line);
    }
    public void mouseExited(java.awt.event.MouseEvent me)
    {
    }
   
    public void mouseEntered(java.awt.event.MouseEvent me)
    {
    }
    public void mouseReleased(java.awt.event.MouseEvent me)
    {
        dragging = false;
    }
    public void mouseClicked(java.awt.event.MouseEvent me)
    {
    }
    public void mousePressed(java.awt.event.MouseEvent me)
    {
        int x = me.getX();
        int y = me.getY();
       
        System.out.println("x="+x+" y="+y);
        if(line.intersects(x,y,1,1)) System.out.println("okeh lah kalo begitu");
        //else System.out.println("ga oke lah kalo begitu");
       
        activeShape = getShapeAtLocation(x, y);
        if(activeShape!=null)
        {
            //prepare to drag
            dragging = true;
            startX = x;
            startY = y;
            startShapeX = (int)activeShape.getX1();
            startShapeY = (int)activeShape.getY1();
            endShapeX = (int)activeShape.getX2();
            endShapeY = (int)activeShape.getY2();
        }
    }
   
    public void mouseMoved(java.awt.event.MouseEvent me)
    {
       
    }
   
    public void mouseDragged(java.awt.event.MouseEvent me)
    {
        int x = me.getX();
        int y = me.getY();
       
        int dx = x-startX;
        int dy = y-startY;
        //System.out.println(me);
        if(dragging)
        {
            line.setLine(startShapeX+dx, startShapeY+dy, endShapeX+dx,endShapeY+dy);
            repaint();
        }
    }   
   
    private Line2D getShapeAtLocation(int x, int y)
    {
        if(line.intersects(x,y,1,1))
        {
            return line;
        }
        return null;
    }
   
    public static void main(String args[])
    {
        JFrame f = new JFrame("kambing");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500,500);
        f.setVisible(true);
        f.getContentPane().add(new ShapeTest());
    }
}

No comments:

Post a Comment