Results 1 to 4 of 4
  1. #1
    Jolee is offline Member
    Join Date
    Mar 2009
    Posts
    4
    Rep Power
    0

    Question Help with creating, selecting and dragging a circle

    Hi I have wirrten some code that should allow the user to click on a panel and in doing so draws a circle. The user can then click that circle, selecting it (this can be showed by a change of colour), then drag that circle to a new position. However this is not working in my code. I really need some help.


    Java Code:
    package finalproject;
    
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Shape;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.Ellipse2D;
    import java.util.ArrayList;
    import javax.swing.BorderFactory;
    import javax.swing.JPanel;
    
    /**
    *
    */
    public class PicturePanel extends JPanel implements MouseListener, MouseMotionListener {
    
    public PicturePanel() {
    this.setBorder(BorderFactory.createLoweredBevelBorder());
    this.addMouseListener(this);
    this.addMouseMotionListener(this);
    setPreferredSize(new Dimension(250, 150));
    setVisible(true);
    
    }
    
    @Override
    public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    for (Shape s : shapes) {
    if (s == selectedShape) {
    g2.setColor(Color.GREEN);
    g2.fill(s);
    g2.setColor(Color.BLACK);
    g2.draw(s);
    }
    g2.setColor(Color.RED);
    g2.fill(s);
    g2.setColor(Color.BLACK);
    g2.draw(s);
    }
    }
    ArrayList<Point> pointsLeft = new ArrayList<Point>();
    ArrayList<Point> pointsRight = new ArrayList<Point>();
    public int lx, ly, rx, ry;
    public Point eR1, eR2 , eL1 , eL2 ;
    public Point lil;
    public Point lil2;
    ArrayList<Shape> shapes = new ArrayList<Shape>();
    private Shape selectedShape = null;
    
    public void mouseClicked(MouseEvent e) {
    if (e.getSource() == RunProgram.pic1) {
    
    if (selectedShape != null) {
    drawSelectedLeft(eL1.x, eL1.y);
    } else if (hitTest(e.getPoint()) == null) {
    eL1 = e.getPoint();
    //pointsLeft.add(eL1);
    lx = eL1.x;
    ly = eL1.y;
    drawCircleLeft(eL1.x, eL1.y);
    System.out.println("eL1 = " + eL1);
    }
    
    }
    }
    
    public void printPointsLeft() {
    System.out.println(pointsLeft);
    }
    
    public void printPointsRight() {
    System.out.println(pointsRight);
    }
    //method to determine which shape is under the cursor using the contains()
    //method of each Shape against your mouse coordinates
    private Shape hitTest(Point p) {
    Shape hitShape = null;
    for (Shape testShape : shapes) {
    if (testShape.contains(p)) {
    hitShape = testShape;
    break;
    }
    }
    return hitShape;
    }
    
    private void moveC(int x, int y) {
    if (eL1.x != x || eL1.y != y) {
    eL1.x = x;
    eL1.y = y;
    repaint(lx + (x - lx), ly + (y - ly), (2 * radius), (2 * radius));
    }
    }
    
    public void mouseDragged(MouseEvent e) {
    dragging = true;
    if (selectedShape != null) {
    moveC(e.getX(), e.getY());
    }
    }
    
    public void drawCircleLeft(int x, int y) {
    Shape circle = new Ellipse2D.Double(x - radius, y - radius, 2 * radius, 2 * radius);
    shapes.add(circle);
    repaint(x - radius, y - radius, 2 * radius, 2 * radius);
    }
    
    public void drawSelectedLeft(int x, int y) {
    Shape circle = new Ellipse2D.Double(x - radius, y - radius, 2 * radius, 2 * radius);
    selectedShape = circle;
    shapes.add(selectedShape);
    repaint(x - radius, y - radius, 2 * radius, 2 * radius);
    }
    
    public void drawCircleRight(int x, int y) {
    Shape circle = new Ellipse2D.Double(x - radius, y - radius, 2 * radius, 2 * radius);
    shapes.add(circle);
    repaint(x - radius, y - radius, 2 * radius, 2 * radius);
    }
    
    public void mousePressed(MouseEvent e) {
    if (e.getSource() == RunProgram.pic1) {
    selectedShape = hitTest(e.getPoint());
    startPoint = e.getPoint();
    lx = startPoint.x;
    ly = startPoint.y;
    dragging = false;
    }
    if (e.getSource() == RunProgram.pic2) {
    selectedShape = hitTest(e.getPoint());
    startPoint = e.getPoint();
    rx = startPoint.x;
    ry = startPoint.y;
    dragging = false;
    }
    }
    
    public void mouseReleased(MouseEvent e) {
    selectedShape = null;
    }
    
    public void mouseExited(MouseEvent e) {
    }
    int x, y;
    int radius = 10;
    private boolean dragging = false;
    Point startPoint;
    
    public void mouseMoved(MouseEvent e) {
    }
    
    public void mouseEntered(MouseEvent e) {
    }
    }

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JLabel;
    
    public class RunProgram extends JFrame {
    
        static JMenuBar bar;
        File fileL;
        File fileR;
        private JPanel toolPanel;
        JSlider phaseSlider;
        JButton openButton;
        int[] pixArr;
        static PicturePanel pic1, pic2;
    
        /** Creates a new instance of RunProgram */
        public RunProgram() {
            setLayout(new BorderLayout());
    
            //create panel to show original pictures
            pic1 = new PicturePanel();
            pic2 = new PicturePanel();
    
            toolPanel = new JPanel();
            toolPanel.setPreferredSize(new Dimension(100, 50));
    
            //create panel to show the phases
    
            JToolBar toolBar = new JToolBar("Still draggable");
            toolBar = new JToolBar(null, JToolBar.VERTICAL);
            toolBar.setFloatable(false);
    
            add(toolBar, BorderLayout.NORTH);
            add(pic1, BorderLayout.WEST);
            add(pic2, BorderLayout.EAST);
            add(toolBar, BorderLayout.CENTER);
    
        }
    }
    Java Code:
    package finalproject;
    
    public class RunApplication {
        public static void main(String[] args) {
    
            RunProgram prog = new RunProgram();
            prog.setSize(800, 500);
            prog.show();
        }
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

  3. #3
    Jolee is offline Member
    Join Date
    Mar 2009
    Posts
    4
    Rep Power
    0

    Default

    Thank for sending the link. In my code I also use
    Java Code:
    super.paintComponent(g);
    when I remove this then I see a trail when dragging the circle. So the problem i have is that I can click on the panel and it will draw a circle. I cannot however select that circle so when dragging i am just creating new circles. Do you know of a possible solution?

    Thank you

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    I'm not sure what you're trying to do with your code, sorry. Here's a small program I created when I was studying Graphics2D and clicking and moving Shape objects. It takes a Shape object, changes it to a Path2D object and then moves the Path2D object via its transform(AffineTransform) method. Maybe you can get some ideas from this.

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class DragShape extends JPanel {
      private static final Color DRAW_COLOR = Color.black;
      private static final Color FILL_COLOR = Color.blue;
      private static final Color SELECTED_FILL_COLOR = Color.red;
      private static final Stroke PATH_STROKE = new BasicStroke(3);
      public static final int RADIUS = 25;
      
      // List of Shape/Path2D objects to draw and drag
      private List<Path2D> path2DList = new ArrayList<Path2D>();
    
      // maps used to assign colors to each shape
      private Map<Shape, Color> drawColorMap = new HashMap<Shape, Color>();
      private Map<Shape, Color> fillColorMap = new HashMap<Shape, Color>();
    
      public DragShape() {
        MyMouseAdapter myMAdapter = new MyMouseAdapter();
        addMouseListener(myMAdapter);
        addMouseMotionListener(myMAdapter);
      }
    
      @Override
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        Graphics2D g2 = (Graphics2D)g;
        // make drawing smooth
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        for (Path2D path2d : path2DList) {
          g2.setColor(fillColorMap.get(path2d));
          g2.fill(path2d);
          g2.setColor(drawColorMap.get(path2d));
          g2.setStroke(PATH_STROKE);
          g2.draw(path2d);
        }
      }
    
      private class MyMouseAdapter extends MouseAdapter {
        private Path2D selectedPath2D = null;
        private Point2D offset = null;
    
        public void mousePressed(MouseEvent e) {
          for (int i = path2DList.size() - 1; i >= 0; i--) {
            Path2D path = path2DList.get(i);
            
            // if select an existing shape/path
            if (path.contains(e.getPoint())) {
              selectedPath2D = path;
              fillColorMap.put(path, SELECTED_FILL_COLOR);
              Rectangle bounds = path.getBounds();
              offset = new Point2D.Double(
                  bounds.getX() - e.getX(), bounds.getY() - e.getY());
              repaint();
              return;  // exit this method
            }
          }
          
          // if not clicking on existing Shape/path, create a new one
          int x = e.getX() - RADIUS;
          int y = e.getY() - RADIUS;
          int w = 2 * RADIUS;
          int h = w;
          // first create Shape
          Ellipse2D circle = new Ellipse2D.Double(x, y, w, h);
          
          // then place it into a Path2D so it can be transformed easily
          Path2D path = new Path2D.Double(circle);
          path2DList.add(path);
          selectedPath2D = path;
          offset = new Point2D.Double(x - e.getX(), 
              y - e.getY());
          drawColorMap.put(path, DRAW_COLOR);
          fillColorMap.put(path, SELECTED_FILL_COLOR);
          repaint();
        }
    
        public void mouseDragged(MouseEvent e) {
          if (selectedPath2D != null) {
            // get current location of Shape/Path2D 
            Rectangle rect = selectedPath2D.getBounds();
            double x = rect.getX();
            double y = rect.getY();
            
            // get where we want to move it
            int deltaX = (int) (e.getX() - x + offset.getX());
            int deltaY = (int) (e.getY() - y + offset.getY());
            // create a transform
            AffineTransform at = AffineTransform.getTranslateInstance(deltaX, deltaY);
            // use transform to move Path2D
            selectedPath2D.transform(at);
            repaint();
          }
        }
    
        public void mouseReleased(MouseEvent e) {
          if (selectedPath2D != null) {
            fillColorMap.put(selectedPath2D, FILL_COLOR);
            selectedPath2D = null;
            offset = null;
            repaint();
          }
        }
      }
    
      private static void createAndShowGUI() {
        JFrame frame = new JFrame("DragShape Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DragShape());
        frame.getContentPane().setPreferredSize(
            new Dimension(800, 600));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
          }
        });
      }
    }
    Last edited by Fubarable; 08-20-2009 at 02:08 AM.

Similar Threads

  1. drawing a dashed circle
    By Alarmmy in forum SWT / JFace
    Replies: 0
    Last Post: 07-13-2009, 09:46 AM
  2. Replies: 0
    Last Post: 04-05-2009, 01:22 PM
  3. Limiting the Dragging area
    By Preethi in forum New To Java
    Replies: 1
    Last Post: 07-30-2008, 03:51 PM
  4. Scaling-ache and mouse dragging
    By willemjav in forum Java Applets
    Replies: 19
    Last Post: 07-19-2008, 12:17 AM
  5. selecting a record in database
    By ramachandran in forum New To Java
    Replies: 0
    Last Post: 10-25-2007, 07:06 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •