event

Drag and Selection example

With this example we shall show you how to work with MouseListener and MouseMotionListener interfaces in order to handle and monitor mouse events an especially mouse drags. This is a very nice feature to use if your application has many graphical object that the user needs to move around the screen very frequently. It’s is very user friendly to let the user drag the object to perform these kinds of actions.

Basically all you have to do in order to handle mouse drags and mouse moves is:

  • Create a class that implements MouseListener and MouseMotionListener interfaces.
  • Override mouseClicked to handle mouse clicks, mouseEnteredmouseExited methods to check whether your mouse has entered or exited a certain area, mousePressed to monitor the mouse button clicks, mouseReleased to check when the user releases a mouse button.
  • Override mouseDragged method in order to handle mouse drags. Use repaint() method to repaint the object in its new position.

Let’s take a look at the code snippets that follow:

package com.javacodegeeks.snippets.desktop;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;

/*
 * When the user drags within the image, this program 
 * displays a rectangle and a string indicating the bounds of the rectangle.
 */

public class DragD {

    JLabel label;
    static String starFile = "C:/Users/nikos7/Desktop/pic.jpg";

    private void createUi(Container cnt, ImageIcon backgr) {

  cnt.setLayout(new BoxLayout(cnt, BoxLayout.PAGE_AXIS));

  SelectRectangle area = new SelectRectangle(backgr, this);

  cnt.add(area);

  label = new JLabel("");

  label.setLabelFor(area);

  cnt.add(label);

  area.setAlignmentX(Component.LEFT_ALIGNMENT);

  label.setAlignmentX(Component.LEFT_ALIGNMENT); 
    }

    public void updateLabel(Rectangle rect) {

  int w = rect.width;

  int h = rect.height;

  if (w == 0) {

w = 1;

  }

  if (h == 0) {

h = 1;

  }

  label.setText("Rectangle extends from (" + rect.x + ", " + rect.y

    + ") to (" + (rect.x + w - 1) + ", "

    + (rect.y + h - 1) + ").");
    }

    protected static ImageIcon createBachground(String path) {

  return new ImageIcon(path);
    }

    private static void createGUI() {

  JFrame.setDefaultLookAndFeelDecorated(true);

  JFrame frame = new JFrame("DragDemo");

  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  DragD controller = new DragD();

  controller.createUi(frame.getContentPane(), createBachground(starFile));

  frame.pack();

  frame.setVisible(true);
    }

    public static void main(String[] args) {

  javax.swing.SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

    createGUI();

}

  });
    }

    private class SelectRectangle extends JLabel {

  Rectangle curRect = null;

  Rectangle rectDraw = null;

  Rectangle prevRectDrawn = new Rectangle();

  DragD drag;

  public SelectRectangle(ImageIcon icon, DragD ctlr) {

//In order to dispay the image

super(icon);

this.drag = ctlr;

setOpaque(true);

setMinimumSize(new Dimension(4,4)); 

MListener mylistn = new MListener();

addMouseListener(mylistn);

addMouseMotionListener(mylistn);

  }

  private class MListener extends MouseInputAdapter {

@Override

public void mousePressed(MouseEvent event) {

    int x = event.getX();int y = event.getY();

    curRect = new Rectangle(x, y, 0, 0);

    updateDrawableRect(getWidth(), getHeight());

    repaint();

}

@Override

public void mouseDragged(MouseEvent e) {

    updateSize(e);

}

@Override

public void mouseReleased(MouseEvent e) {

    updateSize(e);

}

void updateSize(MouseEvent e) {

    int x = e.getX();

    int y = e.getY();

    curRect.setSize(x - curRect.x, y - curRect.y);

    updateDrawableRect(getWidth(), getHeight());

    Rectangle totalRepaint = rectDraw.union(prevRectDrawn);

    repaint(totalRepaint.x, totalRepaint.y, totalRepaint.width,

totalRepaint.height);

}

  }

  @Override

  protected void paintComponent(Graphics grapgic) {

// setup the backgroud

super.paintComponent(grapgic); 

if (curRect != null) {

    grapgic.setXORMode(Color.white); 

    grapgic.drawRect(rectDraw.x, rectDraw.y, rectDraw.width - 1,

rectDraw.height - 1);

    drag.updateLabel(rectDraw);

}

  }

  private void updateDrawableRect(int compW, int compH) {

int x = curRect.x;

int y = curRect.y;

int w = curRect.width;

int h = curRect.height;

if (w < 0) {

    w = 0 - w;

    x = x - w + 1;

    if (x < 0) {

  w += x;

  x = 0;

    }

}

if (h < 0) {

    h = 0 - h;

    y = y - h + 1;

    if (y < 0) {

  h += y;

  y = 0;

    }

}

if ((x + w) > compW) {

    w = compW - x;

}

if ((y + h) > compH) {

    h = compH - y;

}

if (rectDraw != null) {

    prevRectDrawn.setBounds(rectDraw.x, rectDraw.y,

rectDraw.width, rectDraw.height);

    rectDraw.setBounds(x, y, w, h);

} else {

    rectDraw = new Rectangle(x, y, w, h);

}

  }
    }
}

 
This was an example on how to work with drag and selection operations in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button