Hi, I have written some code which when a mouse is clicked, a red circle is drawn at that position. The x,y coordinates are stored in an ArrayList. What I now want to do is enable the circles to be selected and then dragged. When the mouse is released the new coordinates need to replace the old coordinates. I hope someone can help! thanks

ArrayList<Point> pointsLeft = new ArrayList<Point>();
ArrayList<Point> pointsRight = new ArrayList<Point>();

    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == picture1) {
            pointsLeft.add(e.getPoint());
            drawCircleLeft(e.getX(), e.getY());
            printPointsLeft();
            repaint();
        }
        if (e.getSource() == picture2) {
            pointsRight.add(e.getPoint());
            drawCircleRight(e.getX(), e.getY());
            printPointsRight();
            repaint();
        }

    }

    public void printPointsLeft() {
        System.out.println(pointsLeft);
    }
    
        public void printPointsRight() {
        System.out.println(pointsRight);
    }

    public void drawCircleLeft(int x, int y) {
        Graphics g1 = picture1.getGraphics();
        g1.setColor(Color.RED);
        g1.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
        g1.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }

    int x,      y;
    int radius = 5;

    public void drawCircleRight(int x, int y) {
        Graphics g2 = picture2.getGraphics();
        g2.setColor(Color.RED);
        g2.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
        g2.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }

    public void mousePressed(MouseEvent e) {}

    public void mouseReleased(MouseEvent e) {}

    public void mouseEntered(MouseEvent e) {}

    public void mouseExited(MouseEvent e) {}

    public void mouseDragged(MouseEvent e) {}

    public void mouseMoved(MouseEvent e) {}

Recommended Answers

All 28 Replies

Here (basically unedited) is some code from an old program I wrote that allows an object to be dragged around the screen. Perhaps you can use it as a start point?

private int startDragX, startDragY;
private boolean draggable = false, dragging = false, dragged = false;

public void mousePressed(MouseEvent e) {
  startDragX = e.getX(); // in case this is the start of a drag
  startDragY = e.getY();
  dragging = false;
  // System.out.println(startDragX + " x " + startDragY);
 }

 public void mouseReleased(MouseEvent e) {
  // System.out.println("we had a move to " + e.getX() + " x " e.getY());
  this.setLocation(this.getX() + (e.getX() - startDragX), this.getY()
	  + (e.getY() - startDragY));
  repaint();
}

public void mouseDragged(MouseEvent e) {

  if (!dragging) { // this is the start of a drag event sequence
                 // ignore if drag moves less than a pixel or two...
    if (Math.abs(startDragX - e.getX()) + Math.abs(startDragY - e.getY()) > 4) {
    // System.out.println("we are dragging from " + startDragX + " x
    // " + startDragY);
    }
    dragging = true;
  }
  if (dragging) { // drag in progress
    // System.out.println("we are at " + e.getX() + " x " + e.getY());
    this.setLocation(this.getX() + (e.getX() - startDragX), this.getY()
	 + (e.getY() - startDragY)); // for user feedback
  }
}

I understand the code you have given, but how would I visualise the dragging?

By adding a repaint() call in mouseDragged() as well.

Works for me without the repaint, setLocation will trigger one anyway - the one in the mousereleased is there for a completely different (irrelevant here) reason.

Moving an actual component would trigger a repaint automatically, but it looks like he is "dragging" a shape that's been painted on the component, which would require a repaint() to update the location.

This is the code I have, however I am still unable to drag the circles I have drawn. This isn't the complete code. Thanks!

ArrayList<Point> pointsLeft = new ArrayList<Point>();
    ArrayList<Point> pointsRight = new ArrayList<Point>();

    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == picture1) {
            pointsLeft.add(e.getPoint());
            drawCircleLeft(e.getX(), e.getY());
            printPointsLeft();
            repaint();
        }
        if (e.getSource() == picture2) {
            pointsRight.add(e.getPoint());
            drawCircleRight(e.getX(), e.getY());
            printPointsRight();
            repaint();
        }
    }

    public void printPointsLeft() {
        System.out.println(pointsLeft);
    }
    
        public void printPointsRight() {
        System.out.println(pointsRight);
    }

    public void drawCircleLeft(int x, int y) {
        Graphics g1 = picture1.getGraphics();
        g1.setColor(Color.RED);
        g1.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
        g1.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }

    public void drawCircleRight(int x, int y) {
        Graphics g2 = picture2.getGraphics();
        g2.setColor(Color.RED);
        g2.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
        g2.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }

    public void mousePressed(MouseEvent e) {
        startDragX = e.getX();
        startDragY = e.getY();
        dragging = false;
    }

    public void mouseReleased(MouseEvent e) {
        this.setLocation(this.getX() + (e.getX() - startDragX), this.getY() 
                + (e.getY() - startDragY));
        repaint();
    }

    public void mouseDragged(MouseEvent e) {
        if (!dragging){
            if(Math.abs(startDragX - e.getX()) + Math.abs(startDragY - e.getY())> 4){
                System.out.println("We are dragging from" + startDragX + " x" 
                        + startDragY + " y" );
            }
            dragging = true;
        }
        if (dragging){
            System.out.println("We are at" + e.getX() + " x" + e.getY() + " y");
            this.setLocation(this.getX() + (e.getX() - startDragX), this.getY() 
                    + (e.getY() - startDragY));
        }
        repaint();
    }

    public void mouseExited(MouseEvent e) {
    }
    
    int x, y;
    int radius = 5;
ImageIcon largeImage;
private int startDragX, startDragY;
private boolean draggable = false, dragging = false, dragged = false;


    public void mouseMoved(MouseEvent e) {}

    public void mouseEntered(MouseEvent e) {
    }

Moving an actual component would trigger a repaint automatically, but it looks like he is "dragging" a shape that's been painted on the component, which would require a repaint() to update the location.

Yes, I agree. Like I said, that was just some code that I happened to have that could possibly be a starting point for the OP. I was dragging a whole JFrame.

OP: In the new mouse events you need to re-draw your circle at the new coords - this should replace my this.setLocation calls

I have adapted the code to redraw the circle at the new positions, however what happens I can click the panel and the circle will be drawn, but when I click the panel again to drag the circle a line of circles are drawn from the left hand corner of the panel, not where I clicked the mouse. Also what I want is to click a cirlce then be able to hold it and move it to another position, while all the time that circle which was originally drawn is still visible.

/*
 * RunProgram.java
 *
 * Created on 04 November 2008, 17:46
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package finalproject;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.JLabel;
import javax.swing.event.*;

/**
 *
 * @author
 */
public class RunProgram extends JPanel implements ActionListener, ChangeListener, MouseListener, MouseMotionListener {

    static JMenuBar bar;
    private JMenuItem fileOpen;
    private JPanel phasePanel;
    static JPanel contentPane;
    private JPanel picture1;
    private JPanel picture2;
    private JFileChooser fileChooser;
    File file;
    private JLabel leftPic;
    private JLabel rightPic;
    private JPanel toolPanel;
    JButton openButton;
    JSlider phaseSlider;
    JButton t;
    private JButton openRight,  openLeft;

    /** Creates a new instance of RunProgram */
    public RunProgram() {
        setLayout(new BorderLayout());
        bar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        bar.add(fileMenu);

        fileOpen = new JMenuItem("Open");
        fileMenu.add(fileOpen);
        fileOpen.addActionListener(this);

        //Create a panel and make it the content pane.
        contentPane = new JPanel(new BorderLayout());
        contentPane.setBorder(BorderFactory.createRaisedBevelBorder());

        //create panel to show original pictures
        picture1 = new JPanel();
        picture1.addMouseListener(this);
        picture1.addMouseMotionListener(this);
        // picture1.setBackground(Color.BLUE);
        picture1.setBorder(BorderFactory.createLoweredBevelBorder());
        picture1.setPreferredSize(new Dimension(450, 1000));

        picture2 = new JPanel();
        picture2.addMouseListener(this);
        picture2.addMouseMotionListener(this);
        //picture2.setBackground(Color.GREEN);
        picture2.setBorder(BorderFactory.createLoweredBevelBorder());
        picture2.setPreferredSize(new Dimension(450, 1000));

        JPanel controlPanel = new JPanel();
        //controlPanel.setBackground(Color.GRAY);
        controlPanel.setBorder(BorderFactory.createLoweredBevelBorder());
        controlPanel.setPreferredSize(new Dimension(800, 50));
        controlPanel.setLayout(new FlowLayout());

        openLeft = new JButton("<<<Open");
        openLeft.addActionListener(this);
        openRight = new JButton("Open>>>");
        openRight.addActionListener(this);
        picture1.add(openLeft);
        picture2.add(openRight);


        toolPanel = new JPanel();
        toolPanel.setPreferredSize(new Dimension(100, 50));

        //create panel to show the phases
        phasePanel = new JPanel();

        //JScrollPane scroller = new JScrollPane(phasePanel);
        //phasePanel.setBackground(Color.DARK_GRAY);
        phasePanel.setBorder(BorderFactory.createRaisedBevelBorder());
        phasePanel.setLayout(new FlowLayout());
        phasePanel.setPreferredSize(new Dimension(1000, 200));

        JToolBar toolBar = new JToolBar("Still draggable");
        toolBar = new JToolBar(null, JToolBar.VERTICAL);
        toolBar.setFloatable(false);

        //Create the label
        JLabel sliderLabel = new JLabel("Number of Phases", JLabel.CENTER);
        toolBar.add(sliderLabel, BorderLayout.SOUTH);

        toolBar.setPreferredSize(new Dimension(100, 50));
        openButton = new JButton("Open");
        toolBar.add(openButton);
        openButton.addActionListener(this);

        JButton p = new JButton();
        p.setPreferredSize(new Dimension(150, 150));

        JButton q = new JButton();
        q.setPreferredSize(new Dimension(150, 150));

        JButton r = new JButton();
        r.setPreferredSize(new Dimension(150, 150));

        JButton s = new JButton();
        s.setPreferredSize(new Dimension(150, 150));

        contentPane.add(phasePanel, BorderLayout.SOUTH);
        contentPane.add(toolBar, BorderLayout.NORTH);
        contentPane.add(picture1, BorderLayout.WEST);
        contentPane.add(picture2, BorderLayout.EAST);
        contentPane.add(bar, BorderLayout.NORTH);
        contentPane.add(toolBar, BorderLayout.CENTER);
        createPhases(3);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        JFrame frame = new JFrame("ImageViewer");
        frame.add(new RunProgram());
        frame.setSize(1100, 900);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setJMenuBar(bar);
        frame.setContentPane(contentPane);
        frame.setVisible(true);
    }

    /** Listen to the slider. */
    public void stateChanged(ChangeEvent e) {
    }
    
    ArrayList<Point> pointsLeft = new ArrayList<Point>();
    ArrayList<Point> pointsRight = new ArrayList<Point>();

    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == picture1) {
            pointsLeft.add(e.getPoint());
            drawCircleLeft(e.getX(), e.getY());
            printPointsLeft();
            repaint();
        }
        if (e.getSource() == picture2) {
            pointsRight.add(e.getPoint());
            drawCircleRight(e.getX(), e.getY());
            printPointsRight();
            repaint();
        }
    }

    public void printPointsLeft() {
        System.out.println(pointsLeft);
    }
    
        public void printPointsRight() {
        System.out.println(pointsRight);
    }

    public void drawCircleLeft(int x, int y) {
        Graphics g1 = picture1.getGraphics();
        g1.setColor(Color.RED);
        g1.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
        g1.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }

    public void drawCircleRight(int x, int y) {
        Graphics g2 = picture2.getGraphics();
        g2.setColor(Color.RED);
        g2.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
        g2.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }

    public void mousePressed(MouseEvent e) {
        startDragX = e.getX();
        startDragY = e.getY();
        dragging = false;
    }

    public void mouseReleased(MouseEvent e) {
//        System.out.println("we moved to x: " + e.getX() + "y: " + e.getY());
            if (e.getSource() == picture1) {
            pointsLeft.add(e.getPoint());
            drawCircleLeft(this.getX() + (e.getX() - startDragX), this.getY() 
                    + (e.getY() - startDragY));
            printPointsLeft();
            repaint();
        }
        if (e.getSource() == picture2) {
            pointsRight.add(e.getPoint());
            drawCircleRight(this.getX() + (e.getX() - startDragX), this.getY() 
                    + (e.getY() - startDragY));
            printPointsRight();
            repaint();
        }
        repaint();
    }

    public void mouseDragged(MouseEvent e) {
        if (!dragging){//start of a drag evet sequence
            //ignore if drag moves less than a pixel or two...
            if(Math.abs(startDragX - e.getX()) + Math.abs(startDragY - e.getY())> 4){
                System.out.println("We are dragging from" + startDragX + " x" 
                        + startDragY + " y" );
            }
            dragging = true;
        }
        if (dragging){
            //System.out.println("We are at" + e.getX() + " x" + e.getY() + " y");
            if (e.getSource() == picture1) {
            pointsLeft.add(e.getPoint());
            drawCircleLeft(this.getX() + (e.getX() - startDragX), this.getY() 
                    + (e.getY() - startDragY));
            printPointsLeft();
            repaint();
        }
        if (e.getSource() == picture2) {
            pointsRight.add(e.getPoint());
            drawCircleRight(this.getX() + (e.getX() - startDragX), this.getY() 
                    + (e.getY() - startDragY));
            printPointsRight();
            repaint();
        }
        }
        repaint();
    }

    public void mouseExited(MouseEvent e) {
    }
    
    int x, y;
    int radius = 5;
ImageIcon largeImage;
private int startDragX, startDragY;
private boolean draggable = false, dragging = false, dragged = false;


    public void mouseMoved(MouseEvent e) {}

    public void mouseEntered(MouseEvent e) {
    }
}

drawCircleLeft(this.getX() + (e.getX() - startDragX), this.getY()

in this line (and any others like it) you need to replace the this.getX() with the original X coord of your circle, ditto the Y coord. You need to store the original coords in the mousePressed event. What we are doing here is computing the latest position of the circle as original position + (distance the mouse has moved)

Thank you, I've done that and it works correctly. However right now what is does is it behaves like a paint brush, painting the first last and the dragging of the mouse. How would I only make visible only one circle moving, rather than the path it takes?

Here if the code so far:

/*
 * RunProgram.java
 *
 * Created on 04 November 2008, 17:46
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package finalproject;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.JLabel;
import javax.swing.event.*;

/**
 *
 * @author
 */
public class RunProgram extends JPanel implements ActionListener, ChangeListener, MouseListener, MouseMotionListener {

    static JMenuBar bar;
    private JMenuItem fileOpen;
    private JPanel phasePanel;
    static JPanel contentPane;
    private JPanel picture1;
    private JPanel picture2;
    File file;
    private JLabel leftPic;
    private JLabel rightPic;
    private JPanel toolPanel;
    JButton openButton;
    JButton t;
    private JButton openRight,  openLeft;

    /** Creates a new instance of RunProgram */
    public RunProgram() {
        setLayout(new BorderLayout());
        bar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        bar.add(fileMenu);

        fileOpen = new JMenuItem("Open");
        fileMenu.add(fileOpen);
        fileOpen.addActionListener(this);

        //Create a panel and make it the content pane.
        contentPane = new JPanel(new BorderLayout());
        contentPane.setBorder(BorderFactory.createRaisedBevelBorder());

        //create panel to show original pictures
        picture1 = new JPanel();
        picture1.addMouseListener(this);
        picture1.addMouseMotionListener(this);
        picture1.setBorder(BorderFactory.createLoweredBevelBorder());
        picture1.setPreferredSize(new Dimension(450, 1000));

        picture2 = new JPanel();
        picture2.addMouseListener(this);
        picture2.addMouseMotionListener(this);
        //picture2.setBackground(Color.GREEN);
        picture2.setBorder(BorderFactory.createLoweredBevelBorder());
        picture2.setPreferredSize(new Dimension(450, 1000));

        JPanel controlPanel = new JPanel();
        controlPanel.setBorder(BorderFactory.createLoweredBevelBorder());
        controlPanel.setPreferredSize(new Dimension(800, 50));
        controlPanel.setLayout(new FlowLayout());

        openLeft = new JButton("<<<Open");
        openLeft.addActionListener(this);
        openRight = new JButton("Open>>>");
        openRight.addActionListener(this);
        picture1.add(openLeft);
        picture2.add(openRight);


        toolPanel = new JPanel();
        toolPanel.setPreferredSize(new Dimension(100, 50));

        //create panel to show the phases
        phasePanel = new JPanel();

        phasePanel.setBorder(BorderFactory.createRaisedBevelBorder());
        phasePanel.setLayout(new FlowLayout());
        phasePanel.setPreferredSize(new Dimension(1000, 200));

        JToolBar toolBar = new JToolBar("Still draggable");
        toolBar = new JToolBar(null, JToolBar.VERTICAL);
        toolBar.setFloatable(false);

        //Create the label
        JLabel sliderLabel = new JLabel("Number of Phases", JLabel.CENTER);
        toolBar.add(sliderLabel, BorderLayout.SOUTH);

        phaseSlider = new JSlider(1, 6);
        phaseSlider.setMajorTickSpacing(1);
        phaseSlider.setPaintTicks(true);
        phaseSlider.setPaintLabels(true);
        phaseSlider.addChangeListener(this);

        toolBar.add(phaseSlider, BorderLayout.SOUTH);

        toolBar.setPreferredSize(new Dimension(100, 50));
        openButton = new JButton("Open");
        toolBar.add(openButton);
        openButton.addActionListener(this);

        contentPane.add(phasePanel, BorderLayout.SOUTH);
        contentPane.add(toolBar, BorderLayout.NORTH);
        contentPane.add(picture1, BorderLayout.WEST);
        contentPane.add(picture2, BorderLayout.EAST);
        contentPane.add(bar, BorderLayout.NORTH);
        contentPane.add(toolBar, BorderLayout.CENTER);
        createPhases(3);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        JFrame frame = new JFrame("ImageViewer");
        frame.add(new RunProgram());
        frame.setSize(1100, 900);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setJMenuBar(bar);
        frame.setContentPane(contentPane);
        frame.setVisible(true);
    }

    ArrayList<Point> pointsLeft = new ArrayList<Point>();
    ArrayList<Point> pointsRight = new ArrayList<Point>();
    int lx, ly, rx, ry;

    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == picture1) {
            pointsLeft.add(e.getPoint());
            lx = e.getX();
            ly = e.getY();
            drawCircleLeft(lx, ly);
            printPointsLeft();
            repaint();
        }
        if (e.getSource() == picture2) {
            pointsRight.add(e.getPoint());
            rx = e.getX();
            ry = e.getY();
            drawCircleRight(rx, ry);
            printPointsRight();
            repaint();
        }
    }

    public void printPointsLeft() {
        System.out.println(pointsLeft);
    }
    
   public void printPointsRight() {
        System.out.println(pointsRight);
    }

    public void drawCircleLeft(int x, int y) {
        Graphics g1 = picture1.getGraphics();
        g1.setColor(Color.RED);
        g1.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
        g1.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }

    public void drawCircleRight(int x, int y) {
        Graphics g2 = picture2.getGraphics();
        g2.setColor(Color.RED);
        g2.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
        g2.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }

    public void mousePressed(MouseEvent e) {
        if (e.getSource() == picture1) {
            startPoint = e.getPoint();
            lx = startPoint.x;
            ly = startPoint.y;
            dragging = false;
        }
        if (e.getSource() == picture1) {
            startPoint = e.getPoint();
            rx = startPoint.x;
            ry = startPoint.y;
            dragging = false;
        }
    }

    public void mouseReleased(MouseEvent e) {
//        System.out.println("we moved to x: " + e.getX() + "y: " + e.getY());
        if (e.getSource() == picture1) {
            pointsLeft.add(e.getPoint());
            drawCircleLeft(lx + (e.getX() - lx), ly + (e.getY() - ly));
            printPointsLeft();
            repaint();
        }
        if (e.getSource() == picture2) {
            pointsRight.add(e.getPoint());
            drawCircleRight(rx + (e.getX() - rx), ry + (e.getY() - ry));
            printPointsRight();
            repaint();
        }
        repaint();
    }


    public void mouseDragged(MouseEvent e) {
        if (!dragging) {//start of a drag evet sequence
            //ignore if drag moves less than a pixel or two...
            if (Math.abs(startDragX - e.getX()) + Math.abs(startDragY - e.getY()) > 4) {
                System.out.println("We are dragging from" + startDragX + " x" + startDragY + " y");
            }
            dragging = true;
        }
        if (dragging) {
            //System.out.println("We are at" + e.getX() + " x" + e.getY() + " y");
            if (e.getSource() == picture1) {
                pointsLeft.add(e.getPoint());
                drawCircleLeft(lx + (e.getX() - lx), ly + (e.getY() - ly));
                printPointsLeft();
                repaint();
            }
            if (e.getSource() == picture2) {
                pointsRight.add(e.getPoint());
                drawCircleRight(rx + (e.getX() - rx), ry + (e.getY() - ry));
                printPointsRight();
                repaint();
            }
        }
        repaint();
    }

    public void mouseExited(MouseEvent e) {
    }
    int x,  y;
    int radius = 5;
    ImageIcon largeImage;
    private  int startDragX,    startDragY;
    private  boolean draggable = false,    dragging = false,    dragged = false;
    Point startPoint;

    public void mouseMoved(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }
}

I guess, in your drawCircle methods you need to clear the previous contents before drawing the circle at its new coords.

I'm still working on the clearing the previous contents. But at the moment I want to have a separate class for running this application and another class for the contents of the frame, however because originally my RunProgram class extends a JPanel and I have the code

frame.setContentPane(contentPane);

to set the contentpane. Now I have change the RunProgram class to extend a JFrame and I have removed the main method and put it in another class, how can I now set the contentPane in a separate class?

Here's the example:

public class RunApplication{
      public static void main(String[] args){
          RunProgram p = new RunProgram();
          p.setSize(1100,900);
          p.setVisible(true);
      }
}

I need to set the content pane because nothing will show but the frame.

Not enough info for a proper answer, but probably you need to create a public method that sets the content pane, then you can call that method from a different class. (Normally you don't need to set the content pane, JFrame has one by default.)

I figured out how to do it, but there's still another problem. I may try what you suggested but at the moment instead of creating a panel and making it the contentPane, I used the default contentpane. And now the frame and the contents display. The problem now is when I click on the panel the red circle is drawn then immediately disappears. Do you know why this is?

Thanks

Here is my code, I've removed parts of it to make it easier to read, but it should run.

/*
 * RunProgram.java
 *
 * Created on 04 November 2008, 17:46
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package finalproject;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.JLabel;
import javax.swing.event.*;

/**
 *
 * @author
 */
public class RunProgram extends JFrame implements ActionListener, ChangeListener, MouseListener, MouseMotionListener {

    static JMenuBar bar;
    private JMenuItem fileOpen;
    private JPanel phasePanel;
    private JPanel picture1;
    private JPanel picture2;
    private JFileChooser fileChooser;
    File file;
    private JLabel leftPic;
    private JLabel rightPic;
    private JPanel toolPanel;
    JButton openButton;
    JSlider phaseSlider;
    JButton t;
    private JButton openRight,  openLeft;

    /** Creates a new instance of RunProgram */
    public RunProgram() {
        setLayout(new BorderLayout());
        bar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        bar.add(fileMenu);

        fileOpen = new JMenuItem("Open");
        fileMenu.add(fileOpen);
        fileOpen.addActionListener(this);

        //create panel to show original pictures
        picture1 = new JPanel();
        picture1.addMouseListener(this);
        picture1.addMouseMotionListener(this);
        picture1.setBorder(BorderFactory.createLoweredBevelBorder());
        picture1.setPreferredSize(new Dimension(450, 1000));

        picture2 = new JPanel();
        picture2.addMouseListener(this);
        picture2.addMouseMotionListener(this);
        //picture2.setBackground(Color.GREEN);
        picture2.setBorder(BorderFactory.createLoweredBevelBorder());
        picture2.setPreferredSize(new Dimension(450, 1000));

        JPanel controlPanel = new JPanel();
        controlPanel.setBorder(BorderFactory.createLoweredBevelBorder());
        controlPanel.setPreferredSize(new Dimension(800, 50));
        controlPanel.setLayout(new FlowLayout());

        openLeft = new JButton("<<<Open");
        openLeft.addActionListener(this);
        openRight = new JButton("Open>>>");
        openRight.addActionListener(this);
        picture1.add(openLeft);
        picture2.add(openRight);


        toolPanel = new JPanel();
        toolPanel.setPreferredSize(new Dimension(100, 50));

        //create panel to show the phases
        phasePanel = new JPanel();

        phasePanel.setBorder(BorderFactory.createRaisedBevelBorder());
        phasePanel.setLayout(new FlowLayout());
        phasePanel.setPreferredSize(new Dimension(1000, 200));

        JToolBar toolBar = new JToolBar("Still draggable");
        toolBar = new JToolBar(null, JToolBar.VERTICAL);
        toolBar.setFloatable(false);

        //Create the label
        JLabel sliderLabel = new JLabel("Number of Phases", JLabel.CENTER);
        toolBar.add(sliderLabel, BorderLayout.SOUTH);

        phaseSlider = new JSlider(1, 6);
        phaseSlider.setMajorTickSpacing(1);
        phaseSlider.setPaintTicks(true);
        phaseSlider.setPaintLabels(true);
        phaseSlider.addChangeListener(this);

        toolBar.add(phaseSlider, BorderLayout.SOUTH);

        toolBar.setPreferredSize(new Dimension(100, 50));
        openButton = new JButton("Open");
        toolBar.add(openButton);
        openButton.addActionListener(this);

        getContentPane().add(phasePanel, BorderLayout.SOUTH);
        getContentPane().add(toolBar, BorderLayout.NORTH);
        getContentPane().add(picture1, BorderLayout.WEST);
        getContentPane().add(picture2, BorderLayout.EAST);
        getContentPane().add(bar, BorderLayout.NORTH);
        getContentPane().add(toolBar, BorderLayout.CENTER);
    }


    public void actionPerformed(ActionEvent e) {
}

    ArrayList<Point> pointsLeft = new ArrayList<Point>();
    ArrayList<Point> pointsRight = new ArrayList<Point>();
    int lx, ly, rx, ry;

    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == picture1) {
            pointsLeft.add(e.getPoint());
            lx = e.getX();
            ly = e.getY();
            drawCircleLeft(lx, ly);
            printPointsLeft();
            repaint();
        }
        if (e.getSource() == picture2) {
            pointsRight.add(e.getPoint());
            rx = e.getX();
            ry = e.getY();
            drawCircleRight(rx, ry);
            printPointsRight();
            repaint();
        }
    }

    public void printPointsLeft() {
        System.out.println(pointsLeft);
    }
    
   public void printPointsRight() {
        System.out.println(pointsRight);
    }

    public void drawCircleLeft(int x, int y) {
        Graphics g1 = picture1.getGraphics();
        g1.setColor(Color.RED);
        g1.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
        g1.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }

    public void drawCircleRight(int x, int y) {
        Graphics g2 = picture2.getGraphics();
        g2.setColor(Color.RED);
        g2.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
        g2.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }

    public void mousePressed(MouseEvent e) {
        if (e.getSource() == picture1) {
            startPoint = e.getPoint();
            lx = startPoint.x;
            ly = startPoint.y;
            dragging = false;
        }
        if (e.getSource() == picture1) {
            startPoint = e.getPoint();
            rx = startPoint.x;
            ry = startPoint.y;
            dragging = false;
        }
    }

    public void mouseReleased(MouseEvent e) {
//        System.out.println("we moved to x: " + e.getX() + "y: " + e.getY());
        if (e.getSource() == picture1) {
            pointsLeft.add(e.getPoint());
            drawCircleLeft(lx + (e.getX() - lx), ly + (e.getY() - ly));
            printPointsLeft();
            repaint();
        }
        if (e.getSource() == picture2) {
            pointsRight.add(e.getPoint());
            drawCircleRight(rx + (e.getX() - rx), ry + (e.getY() - ry));
            printPointsRight();
            repaint();
        }
        repaint();
    }


    public void mouseDragged(MouseEvent e) {
        if (!dragging) {//start of a drag evet sequence
            //ignore if drag moves less than a pixel or two...
            if (Math.abs(startDragX - e.getX()) + Math.abs(startDragY - e.getY()) > 4) {
                System.out.println("We are dragging from" + startDragX + " x" + startDragY + " y");
            }
            dragging = true;
        }
        if (dragging) {
            //System.out.println("We are at" + e.getX() + " x" + e.getY() + " y");
            if (e.getSource() == picture1) {
                pointsLeft.add(e.getPoint());
                drawCircleLeft(lx + (e.getX() - lx), ly + (e.getY() - ly));
                printPointsLeft();
                repaint();
            }
            if (e.getSource() == picture2) {
                pointsRight.add(e.getPoint());
                drawCircleRight(rx + (e.getX() - rx), ry + (e.getY() - ry));
                printPointsRight();
                repaint();
            }
        }
        repaint();
    }

    public void mouseExited(MouseEvent e) {
    }
    int x,  y;
    int radius = 5;
    ImageIcon largeImage;
    private  int startDragX,    startDragY;
    private  boolean dragging = false;
    Point startPoint;

    public void mouseMoved(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }
}
package finalproject;
/**
 *
 *
 */
public class RunApplication {
    public static void main(String[] args) {

        RunProgram prog = new RunProgram();
        prog.setSize(1100, 900);
        //prog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //frame.setJMenuBar(bar);
       //prog.setContentPane(contentPane);
        prog.show();
        //prog.setVisible(true);
    }
}

Can't immediately see why you have that problem. You'll have to do some more dubugging!
ps: getContentPane().add(... this is not needed since Java 1.5, you can just call add(...

Dragging the drawn circle is working however when I relase the mouse the final position of the circle is not drawn. I have tried a number of things but they do not work. I think it will be something to do with the mouseReleased() method but I'm am not sure what i'll need to include in the method.

This is the section of code which deals with the drawing etc. Do you know what I'll need to include to get the last circle drawn?

Thank you

private static Image imageto;
    ArrayList<Point> pointsLeft = new ArrayList<Point>();
    ArrayList<Point> pointsRight = new ArrayList<Point>();
    public int lx,  ly,  rx,  ry;
    public Point lil;
    public Point lil2;

    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == picture1) {
            lil = e.getPoint();
            pointsLeft.add(lil);
            lx = e.getX();
            ly = e.getY();
            drawCircleLeft(lx, ly);
            printPointsLeft();
            //repaint();
            //picture1.removeAll();
        }
        if (e.getSource() == picture2) {
            lil2 = e.getPoint();
            pointsRight.add(lil2);
            rx = e.getX();
            ry = e.getY();
            drawCircleRight(rx, ry);
            printPointsRight();
            //repaint();
        }
        //align = new AlignFace(rx, ry, lx, ly);
        //align.align();
    }

    public void printPointsLeft() {
        System.out.println(pointsLeft);
    }

    public void printPointsRight() {
        System.out.println(pointsRight);
    }

    public void drawCircleLeft(int x, int y) {
        Graphics g1 = picture1.getGraphics();
        g1.setColor(Color.RED);
        g1.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
        g1.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }

    public void drawCircleRight(int x, int y) {
        Graphics g2 = picture2.getGraphics();
        g2.setColor(Color.RED);
        g2.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
        g2.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
    }

    public void mousePressed(MouseEvent e) {
        if (e.getSource() == picture1) {
            startPoint = e.getPoint();
            lx = startPoint.x;
            ly = startPoint.y;
            dragging = false;
        }
        if (e.getSource() == picture2) {
            startPoint = e.getPoint();
            rx = startPoint.x;
            ry = startPoint.y;
            dragging = false;
        }
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseDragged(MouseEvent e) {
        if (!dragging) {
            if (Math.abs(startDragX - e.getX()) + Math.abs(startDragY - e.getY()) > 4) {
                System.out.println("We are dragging from" + startDragX + " x" + startDragY + " y");
            }
            dragging = true;
        }
        if (dragging) {
            if (e.getSource() == picture1) {
                pointsLeft.add(e.getPoint());
                drawCircleLeft(lx + (e.getX() - lx), ly + (e.getY() - ly));
                printPointsLeft();
                repaint();
            }
            if (e.getSource() == picture2) {
                pointsRight.add(e.getPoint());
                drawCircleRight(rx + (e.getX() - rx), ry + (e.getY() - ry));
                printPointsRight();
                repaint();
            }
        }
    }

    public void mouseExited(MouseEvent e) {
    }

    int x,    y;
    int radius = 5;
    ImageIcon largeImage;
    ImageIcon largeImageL;
    ImageIcon largeImageR;
    private  int startDragX,        startDragY;
    private boolean dragging = false;
    Point startPoint;

    public void mouseMoved(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }

All you need to do to draw the circle in its final position is call repaint, set the coordinates of where you want the circle to be drawn, then draw the circle at that position. You'd put the method calls to do that inside of mouseReleased.

Thanks for the help, I have done this:

public void mouseReleased(MouseEvent e) {
        if (e.getSource() == picture1) {
            drawCircleLeft(e.getPoint().x, e.getPoint().y);
        }
        if (e.getSource() == picture2) {
            drawCircleRight(e.getPoint().x, e.getPoint().y);
        }
    }

However the problem I know have is that if I click the panel twice and try to drag one of the circles drawn, the other dissappears, the same thing happens when I click on picture1 and then picture2, when I then come to drag a circle on picture1 the circle on picture2 dissappears. Do you know why this is?
Thank you

Yeah, I'm pretty sure it's because by calling repaint, you are calling paintComponent, which I believe clears the screen for you before drawing whatever it draws. So you'll either have to redraw everything that you want on the screen (which would require your programremembering what was there) or you'll have to edit paintComponent method so that it does not "erase" the screen. I could be slightly off in my advice here, but I will check a previous thread of mine that contains the correct info and I'll get back to you later tonight. (But I think this is right)

I'm not too sure how I would change the paint method. I however do save the circles drawn in an array list. What method would I then include the code to go through the array list and draw circles at the specified points?

Thanks

If you maintain a list of shapes

List<Shape> shapes = new ArrayList<Shape>();

You can override the paintComponent method to paint them like so

public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D)g;
    for (Shape s : shapes){
        g2.draw(s);
    }
}

If you want to move one of the shapes, your mouse routines first need to determine which shape is under the cursor. You can do that easily by checking the contains() method of each Shape against your mouse coordinates. Here is a method you could use to check them

private Shape hitTest(Point p){
    Shape hitShape = null;
    for (Shape testShape : shapes){
        if (testShape.contains(p)){
            hitShape = testShape;
            break;
        }
    }
    return hitShape;
}

Currently al I am doing is adding the points where the circles are drawn into an array list. With the array list of shapes how would i then save shapes rather than points? Sorry if this seems an stupid question.
Thank you

In your mouse listener methods, create the Shape objects instead of drawing them directly to the screen.

This is my mouseclicked method

public void mouseClicked(MouseEvent e) {
        if (e.getSource() == pic1) {
            if (pointsLeft.isEmpty()) {
                eL1 = e.getPoint();
                //pointsLeft.add(eL1);
                lx = eL1.x;
                ly = eL1.y;
                drawCircleLeft(eL1.x, eL1.y);
                System.out.println("eL1 = " + eL1);

            } else if (pointsLeft.size() == 1) {
                eL2 = e.getPoint();
                //pointsLeft.add(eL2);
                lx = eL2.x;
                ly = eL2.y;
                drawCircleLeft(eL2.x, eL2.y);
                System.out.println("eL2 " + eL2);
            //picture1.removeAll();
            } else if (pointsLeft.size() > 1) {
                System.out.println("Maximum selections");
            }

        }
        if (e.getSource() == pic2) {
            if (pointsRight.isEmpty()) {
                eR1 = e.getPoint();
                pointsRight.add(eR1);
                lx = eR1.x;
                ly = eR1.y;
                drawCircleRight(eR1.x, eR1.y);
                System.out.println("eR1 = " + eR1);

            } else if (pointsRight.size() == 1) {
                eR2 = e.getPoint();
                pointsRight.add(eR2);
                lx = eR2.x;
                ly = eR2.y;
                drawCircleRight(eR2.x, eR2.y);
                System.out.println("eR2 " + eR2);
            } else if (pointsRight.size() > 1) {
                System.out.println("Maximum selections");
            }
        }
    }

and this is my methods to draw the cirlces

public void drawCircleLeft(int x, int y) {
        Graphics2D g1 = (Graphics2D) pic1.getGraphics();
        Shape circle = new Ellipse2D.Double(x - radius, y - radius, 2 * radius, 2 * radius);
        g1.draw(circle);
        g1.setColor(Color.RED);
        g1.fill(circle);
        shapes.add(circle);
    }

    public void drawCircleRight(int x, int y) {
        Graphics2D g2 = (Graphics2D) pic2.getGraphics();
        Shape circle = new Ellipse2D.Double(x - radius, y - radius, 2 * radius, 2 * radius);
        g2.draw(circle);
        g2.setColor(Color.RED);
        g2.fill(circle);
        shapes.add(circle);
    }

You said to create the shapes in my listener method rather than drawing them directly. I'm not sure how I can do this with the methods I have.
Thanks

You should restructure your code a bit to override the paintComponent() method of the JPanel objects you wish to draw to, rather then calling getGraphics() to obtain the graphics context. I gave an example above of how paintComponent() can loop through and render the shapes. Your mouse methods just need to create or modify shapes in the List and call repaint to update the graphics.

I'd recommend looking through this short tutorial on custom painting in Swing to see how to override paintComponent().
http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html

What I don't understand is how I can determine which panel is clicked if I don't use the getGraphics method? I'm not really quite sure how to restructure my code? The problem I am having is that I require separate methods for drawing on the right and left panel.

Here's a small example of a custom JPanel class that keeps a List of Shape objects and lets you drag them with the mouse. Perhaps it will clear up some of your uncertainties

import java.awt.BorderLayout;
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.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class DraggableGraphic extends JFrame {
    
    private JPanel paintPanel;

    public DraggableGraphic() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setMinimumSize(new Dimension(300, 300));

        paintPanel = new  PaintPanel();
        getContentPane().add(paintPanel, BorderLayout.CENTER);
        pack();
    }

    class PaintPanel extends JPanel implements MouseMotionListener,MouseListener {
        private List<Shape> shapes;
        private Shape mouseOverShape=null;
        
        public PaintPanel(){
            super();
            addMouseListener(this);
            addMouseMotionListener(this);

            shapes = new ArrayList<Shape>();
            shapes.add(new Ellipse2D.Float(25, 15, 60, 30));
            shapes.add(new Ellipse2D.Float(75, 35, 60, 30));
        }
        
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            for (Shape s : shapes){
                g2.draw(s);
            }
        }

        public void mouseDragged(MouseEvent e) {
            if (mouseOverShape!=null){
                if(mouseOverShape instanceof RectangularShape){
                    // Move the shape center to the mouse location
                    RectangularShape rShape = (RectangularShape)mouseOverShape;
                    float width = (float)rShape.getWidth();
                    float height = (float)rShape.getHeight();
                    rShape.setFrame(new Rectangle2D.Float(e.getX()-width/2, e.getY()-height/2, width, height));
                }
                repaint();
            }
        }

        public void mouseMoved(MouseEvent e) {}

        /** returns the first Shape that contains Point p or null if none contain p */
        private Shape hitTest(Point p){
            Shape hitShape = null;
            for (Shape testShape : shapes){
                if (testShape.contains(p)){
                    hitShape = testShape;
                    break;
                }
            }
            return hitShape;
        }


        public void mousePressed(MouseEvent e) {
            // figure out what shape, if any, that we are clicking on
            mouseOverShape = hitTest(e.getPoint());
        }

        public void mouseReleased(MouseEvent e) {
            mouseOverShape = null;
            repaint();
        }

        public void mouseClicked(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
    }




    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DraggableGraphic().setVisible(true);
            }
        });
    }
}

In your case, with two panels, you would have two instances of this "PaintPanel" and each would be self-contained. Each has its own shapes and handles its own mouse events.

Thank you, I now have it working!
Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.