event

Draw and Drag rectangles

In this example we are going to create a simple application in which you can draw a simple shape (rectangle for example ) and drag it around our canvas. 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 MouseMotionListenerinterfaces.
  • Override mouseClicked to handle mouse clicks, mouseEnteredmouseExitedmethods 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 java.awt.Container;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class DrawSketch extends JPanel implements MouseMotionListener {

    private static final int recW = 14;
    private static final int MAX = 100;
    private Rectangle[] rect = new Rectangle[MAX];
    private int numOfRecs = 0;
    private int currentSquareIndex = -1;

    public DrawSketch() {

  addMouseListener(new MouseAdapter() {

@Override

public void mousePressed(MouseEvent evt) {

    int x = evt.getX();

    int y = evt.getY();

    currentSquareIndex = getRec(x, y);

    if (currentSquareIndex < 0) // not inside a square

    {

  add(x, y);

    }

}

@Override

public void mouseClicked(MouseEvent evt) {

    int x = evt.getX();

    int y = evt.getY();

    if (evt.getClickCount() >= 2) {

  remove(currentSquareIndex);

    }

}

  });

  addMouseMotionListener(this);
    }

    @Override
    public void paintComponent(Graphics g) {

  super.paintComponent(g);

  for (int i = 0; i < numOfRecs; i++) {

((Graphics2D) g).draw(rect[i]);

  }
    }

    public int getRec(int x, int y) {

  for (int i = 0; i < numOfRecs; i++) {

if (rect[i].contains(x, y)) {

    return i;

}

  }

  return -1;
    }

    public void add(int x, int y) {

  if (numOfRecs < MAX) {

rect[numOfRecs] = new Rectangle(x, y, recW, recW);

currentSquareIndex = numOfRecs;

numOfRecs++;

repaint();

  }
    }

    @Override
    public void remove(int n) {

  if (n < 0 || n >= numOfRecs) {

return;

  }

  numOfRecs--;

  rect[n] = rect[numOfRecs];

  if (currentSquareIndex == n) {

currentSquareIndex = -1;

  }

  repaint();
    }

    @Override
    public void mouseMoved(MouseEvent event) {

  int x = event.getX();

  int y = event.getY();

  if (getRec(x, y) >= 0) {

setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));

  } else {

setCursor(Cursor.getDefaultCursor());

  }
    }

    @Override
    public void mouseDragged(MouseEvent event) {

  int x = event.getX();

  int y = event.getY();

  if (currentSquareIndex >= 0) {

Graphics graphics = getGraphics();

graphics.setXORMode(getBackground());

((Graphics2D) graphics).draw(rect[currentSquareIndex]);

rect[currentSquareIndex].x = x;

rect[currentSquareIndex].y = y;

((Graphics2D) graphics).draw(rect[currentSquareIndex]);

graphics.dispose();

  }
    }

    public static void main(String[] args) {

  JFrame jFrame = new JFrame();

  jFrame.setTitle("");

  jFrame.setSize(300, 200);

  jFrame.addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

    System.exit(0);

}

  });

  Container cPane = jFrame.getContentPane();

  cPane.add(new DrawSketch());

  jFrame.setVisible(true);
    }
}

 
This was an example on how to draw and drag a simple shape in a Java Desktop Application.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

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