Moving drawn shape using mouse listener - java

working on a simple Paint java project, its required to draw shapes for example(line , circle , rectangle ,........)
I am trying to write methods where I can move , delete and resize a selected shape.
My code should be right as I already test it at another project that has one drawn rectangle.
my paintComponent method to select shapes and add them to ArrayList
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (ShapeItem item :shapes) {
if (!(item.getShape() instanceof Line2D)){
g2d.setColor(item.getColor());
g2d.fill(item.getShape());
}
else {
// g2d.setStroke(new BasicStroke(10));
g2d.setColor(item.getColor());
g2d.draw(item.getShape());
}
}
if (selectedShape != null){
g2d.setStroke ( new BasicStroke(1f,
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND,
1f,
new float[] {2f},
0f) );
if (selectedShape.getShape() instanceof Ellipse2D) {
Rectangle rect = selectedShape.getShape().getBounds();
g2d.draw(rect);
}
else if (selectedShape.getShape() instanceof Rectangle2D) {
Rectangle2D dotted = new Rectangle2D.Double((int)((Rectangle2D) selectedShape.getShape()).getX() - 6,
(int)((Rectangle2D) selectedShape.getShape()).getY() - 6,
(int)((Rectangle2D) selectedShape.getShape()).getWidth() + 12,
(int)((Rectangle2D) selectedShape.getShape()).getHeight() + 12);
g2d.draw(dotted);
}
else if (selectedShape.getShape() instanceof Line2D) {
Rectangle rect = selectedShape.getShape().getBounds();
g2d.draw(rect);
}
else if (selectedShape.getShape() instanceof Polygon) {
Rectangle rect = selectedShape.getShape().getBounds();
g2d.draw(rect);
}
}
}
Class to move shapes
package draw;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
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.JComponent;
public class DynamicShapes extends JComponent{
/**
*
*/
private static final long serialVersionUID = 1L;
MoveShapes move = new MoveShapes();
public DynamicShapes(){
addMouseListener(move);
addMouseMotionListener(move);
}
class MoveShapes extends MouseAdapter{
private int x;
private int y;
boolean pressed;
boolean dragged;
DrawingPanel d = new DrawingPanel();
#Override
public void mousePressed(MouseEvent e){
super.mousePressed(e);
pressed = false;
for (ShapeItem s : d.getShapes()){
if(s.getShape().contains(e.getX() , e.getY()) ){
pressed = true;
System.out.println("shape is pressed");
}
}
}
#Override
public void mouseDragged(MouseEvent e){
super.mouseDragged(e);
if(pressed){
int dx = e.getX()-x;
int dy = e.getY()-y;
for (ShapeItem s : d.getShapes()){
Rectangle rect = s.getShape().getBounds();
if(s.getShape().getBounds2D().contains(x, y)){
rect.x += dx;
rect.y += dy;
repaint();
}
x += dx;
y += dy;
}
}
}
}
}
if any one can help, I don't have a big understanding of the hole graphics and mouse events as it's my first time :)

Related

How do I make a top down view with the ability to rotate with built in java graphics?

I'm trying to make a racing game with the top down view on a static player in the middle of the screen, so instead of moving the player through the map, the map would move around the player. Since it's a racing game, I wanted it to also be somewhat similar to a car, but I've been having trouble with rotating the map around the player and having that work with translations.
I've tried keeping track of the center by adding or subtracting from it, which is what I did for the translations, but it doesn't work with the rotate method. The rotate function wouldn't rotate about the player and instead would rotate the player around some other point, and the translations would snap to a different location from the rotations. I'm sure my approach is flawed, and I have read about layers and such, but I'm not sure what I can do with them or how to use them. Also, any recommendations as to how to use java graphics in general would be greatly appreciated!
This is what I have in my main:
import javax.swing.JFrame;
import java.awt.BorderLayout;
public class game
{
public static void main(String []args)
{
JFrame frame = new JFrame();
final int FRAME_WIDTH = 1000;
final int FRAME_HEIGHT = 600;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Map b = new Map();
frame.add(b,BorderLayout.CENTER);
frame.setVisible(true);
b.startAnimation();
}
}
And this is the class that handles all the graphics
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Map extends JComponent implements Runnable, KeyListener
{
private int speed = 5;
private int xcenter = 500; // starts on player
private int ycenter = 300;
private double angle = 0.0;
private int[] xcords = {xcenter+10, xcenter, xcenter+20};
private int[] ycords = {ycenter-10, ycenter+20, ycenter+20};
private boolean moveNorth = false;
private boolean moveEast = false;
private boolean moveSouth = false;
private boolean moveWest = false;
public Map()
{
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void startAnimation()
{
Thread t = new Thread(this);
t.start();
}
public void paintComponent(Graphics g)
{
g.fillPolygon(xcords, ycords, 3);
// move screen
if(moveNorth)
{
ycenter += speed;
g.translate(xcenter, ycenter);
}
else if(moveEast)
{
angle += ((1 * Math.PI/180) % (2 * Math.PI));
((Graphics2D) g).rotate(angle, 0, 0);
}
else if(moveSouth)
{
System.out.println(xcenter + ", " + ycenter);
ycenter -= speed;
((Graphics2D) g).rotate(angle, 0, 0);
g.translate(xcenter, ycenter);
}
else if(moveWest)
{
angle -= Math.toRadians(1) % (2 * Math.PI);
((Graphics2D) g).rotate(angle, 0, 0);
}
for(int i = -10; i < 21; i++)
{
g.drawLine(i * 50, -1000, i * 50, 1000);
g.drawLine(-1000, i * 50, 1000, i * 50);
}
g.drawOval(0, 0, 35, 35);
}
public void run()
{
while (true)
{
try
{
if(moveNorth || moveEast || moveSouth || moveWest)
{
repaint();
}
Thread.sleep(10);
}
catch (InterruptedException e)
{
}
}
}
public void keyPressed(KeyEvent e)
{
if(e.getExtendedKeyCode() == 68) // d
{
moveEast = true;
}
else if(e.getExtendedKeyCode() == 87) // w
{
moveNorth = true;
}
else if(e.getExtendedKeyCode() == 65) // a
{
moveWest = true;
}
else if(e.getExtendedKeyCode() == 83) // s
{
moveSouth = true;
}
}
public void keyReleased(KeyEvent e)
{
moveNorth = false;
moveEast = false;
moveSouth = false;
moveWest = false;
}
public void keyTyped(KeyEvent e)
{
}
}
You have to keep in mind that transformations are compounding, so if you rotate the Graphics context by 45 degrees, everything painted after it will be rotated 45 degrees (around the point of rotation), if you rotate it again by 45 degrees, everything painted after it will be rotated a total of 90 degrees.
If you want to paint additional content after a transformation, then you either need to undo the transformation, or, preferably, take a snapshot of the Graphics context and dispose of it (the snapshot) when you're done.
You also need to beware of the point of rotation, Graphics2D#rotate(double) will rotate the Graphics around the point of origin (ie 0x0), which may not be desirable. You can change this by either changing the origin point (ie translate) or using Graphics2D#rotate(double, double, double), which allows you to define the point of rotation.
For example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public class TestPane extends JPanel {
enum Direction {
LEFT, RIGHT;
}
protected enum InputAction {
PRESSED_LEFT, PRESSED_RIGHT, RELEASED_LEFT, RELEASED_RIGHT
}
private BufferedImage car;
private BufferedImage road;
private Set<Direction> directions = new TreeSet<>();
private double directionOfRotation = 0;
public TestPane() throws IOException {
car = ImageIO.read(getClass().getResource("/images/Car.png"));
road = ImageIO.read(getClass().getResource("/images/Road.png"));
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), InputAction.PRESSED_LEFT);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true), InputAction.RELEASED_LEFT);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), InputAction.PRESSED_RIGHT);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), InputAction.RELEASED_RIGHT);
am.put(InputAction.PRESSED_LEFT, new DirectionAction(Direction.LEFT, true));
am.put(InputAction.RELEASED_LEFT, new DirectionAction(Direction.LEFT, false));
am.put(InputAction.PRESSED_RIGHT, new DirectionAction(Direction.RIGHT, true));
am.put(InputAction.RELEASED_RIGHT, new DirectionAction(Direction.RIGHT, false));
Timer timer = new Timer(5, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (directions.contains(Direction.RIGHT)) {
directionOfRotation += 1;
} else if (directions.contains(Direction.LEFT)) {
directionOfRotation -= 1;
}
// No doughnuts for you :P
if (directionOfRotation > 180) {
directionOfRotation = 180;
} else if (directionOfRotation < -180) {
directionOfRotation = -180;
}
repaint();
}
});
timer.start();
}
protected void setDirectionActive(Direction direction, boolean active) {
if (active) {
directions.add(direction);
} else {
directions.remove(direction);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(213, 216);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
drawRoadSurface(g2d);
drawCar(g2d);
g2d.dispose();
}
protected void drawCar(Graphics2D g2d) {
g2d = (Graphics2D) g2d.create();
int x = (getWidth() - car.getWidth()) / 2;
int y = (getHeight() - car.getHeight()) / 2;
g2d.drawImage(car, x, y, this);
g2d.dispose();
}
protected void drawRoadSurface(Graphics2D g2d) {
g2d = (Graphics2D) g2d.create();
// This sets the point of rotation at the center of the window
int midX = getWidth() / 2;
int midY = getHeight() / 2;
g2d.rotate(Math.toRadians(directionOfRotation), midX, midY);
// We then need to offset the top/left corner so that what
// we want draw appears to be in the center of the window,
// and thus will be rotated around it's center
int x = midX - (road.getWidth() / 2);
int y = midY - (road.getHeight() / 2);
g2d.drawImage(road, x, y, this);
g2d.dispose();
}
protected class DirectionAction extends AbstractAction {
private Direction direction;
private boolean active;
public DirectionAction(Direction direction, boolean active) {
this.direction = direction;
this.active = active;
}
#Override
public void actionPerformed(ActionEvent e) {
setDirectionActive(direction, active);
}
}
}
}

Is there a way to draw boundaries that aren't rectangles in java swing?

I'm trying to draw boundaries for a character that I'm moving around on a JFrame. I know how to draw rectangles to establish boundaries, but how could I do this if the area that I want to draw bounds for isn't a rectangle?
Say for example I want to move the green circle around in the square, but the blue diamond represents the boundaries, and the circle cannot go past those bounds. How could I do this?
This is the kind of thing I use for this is line/point collision:
http://www.jeffreythompson.org/collision-detection/line-circle.php
it's pretty mathy but it works nicely and isn't buggy
Just treat your circle as a rectangle and validate if the circle is inside your diamond with the contains method of Rectangle (See docs). Small snipped:
private Rectangle rect = new Rectangle(25, 25, 450, 450);
private Rectangle circle = new Rectangle(250, 250, 50, 50);
if(rect.contains(tmp)) {
// True, if the circle does not touch any square-line
}
A full example of the code:
package circlemoving;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.*;
import javax.swing.*;
public class CircleMoving {
public static void main(String[] args) {
MainPanel mp = new MainPanel();
JFrame jFrame = new JFrame();
jFrame.add(mp);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setVisible(true);
jFrame.pack();
jFrame.addKeyListener(new KeyListener() {
#Override public void keyTyped(KeyEvent e) {}
#Override public void keyReleased(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
mp.update(e.getKeyCode());
}
});
}
private static class MainPanel extends JPanel {
private Rectangle rect = new Rectangle(25, 25, 450, 450);
private Rectangle circle = new Rectangle(250, 250, 50, 50);
public MainPanel() {
setPreferredSize(new Dimension(500, 500));
repaint();
}
#Override
public void paintComponent(Graphics grahpics) {
super.paintComponent(grahpics);
Graphics2D g2d = (Graphics2D) grahpics;
g2d.setStroke(new BasicStroke(1));
g2d.setColor(Color.BLUE);
g2d.drawRect(rect.x, rect.y, rect.width, rect.height);
g2d.setStroke(new BasicStroke(1));
g2d.setColor(Color.RED);
g2d.drawOval(circle.x, circle.y, circle.width, circle.width);
}
public void update(int keyCode) {
int tmpX = circle.x;
int tmpY = circle.y;
switch (keyCode) {
case 39:
tmpX = circle.x + 3;
break;
case 37:
tmpX = circle.x - 3;
break;
case 38:
tmpY = circle.y - 3;
break;
case 40:
tmpY = circle.y + 3;
break;
default:
break;
}
Rectangle tmp = new Rectangle(tmpX, tmpY, circle.width, circle.height);
if(rect.contains(tmp)) {
circle.x = tmpX;
circle.y = tmpY;
repaint();
}
}
}
}
Result:
I created a simple GUI to demonstrate how to use a polygon boundary in a Swing GUI. Here's the GUI.
You can't see in the picture, but you can grab the green circle (the player) with the mouse and drag it anywhere inside the blue diamond (the boundary). The code will not let you drag the player outside the boundary.
Here's what I did.
I created two model classes. One for the boundary, and one for the player. I used this logical model to draw in the view and do calculations in the mouse listener. This is an application of the model / view / controller pattern.
I created a simple Swing GUI with a drawing panel. I calculated where the start of the oval would be so I could keep the center point and radius in the model.
I created a mouse listener class to listen for the mouse press and mouse release.
And here's the code. Hopefully, there's not much to explain. The Polygon class has a method, contains, that checks if a rectangle is completely inside the polygon. I converted the circle to a rectangle in the listener so I could use this method.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Rectangle2D;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
public class PolygonBoundary implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new PolygonBoundary());
}
private Boundary boundary;
private Dimension dpSize;
private Player player;
public PolygonBoundary() {
this.dpSize = new Dimension(400, 400);
Polygon polygon = new Polygon();
polygon.addPoint(200, 0);
polygon.addPoint(0, 200);
polygon.addPoint(200, 400);
polygon.addPoint(400, 200);
this.boundary = new Boundary(polygon, Color.BLUE);
this.player = new Player(200, 200, 24, Color.GREEN);
}
#Override
public void run() {
JFrame frame = new JFrame("Polygon Boundary");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DrawingPanel drawingPanel =
new DrawingPanel(dpSize, boundary, player);
frame.add(drawingPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 1L;
private Boundary boundary;
private Player player;
public DrawingPanel(Dimension size, Boundary boundary,
Player player) {
this.boundary = boundary;
this.player = player;
this.setPreferredSize(size);
Border border = BorderFactory.createLineBorder(
Color.BLACK, 4);
this.setBorder(border);
PlayerMotion playerMotion =
new PlayerMotion(this, boundary, player);
this.addMouseListener(playerMotion);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(boundary.getColor());
g2d.setStroke(new BasicStroke(4f));
g2d.drawPolygon(boundary.getPolygon());
g2d.setColor(player.getColor());
Point center = player.getCenter();
int radius = player.getRadius();
int diameter = radius + radius;
g2d.drawOval(center.x - radius, center.y - radius,
diameter, diameter);
}
}
public class PlayerMotion implements MouseListener {
private Boundary boundary;
private JPanel panel;
private Player player;
private Point originalPoint;
public PlayerMotion(JPanel panel, Boundary boundary,
Player player) {
this.panel = panel;
this.boundary = boundary;
this.player = player;
}
#Override
public void mouseClicked(MouseEvent event) {
}
#Override
public void mousePressed(MouseEvent event) {
Point center = player.getCenter();
int radius = player.getRadius();
Rectangle2D r2d = createRectangle(center, radius);
if (r2d.contains(event.getPoint())) {
originalPoint = event.getPoint();
}
}
#Override
public void mouseReleased(MouseEvent event) {
if (originalPoint == null) {
return;
}
Point endPoint = event.getPoint();
Point center = player.getCenter();
int radius = player.getRadius();
int newX = center.x - originalPoint.x + endPoint.x;
int newY = center.y - originalPoint.y + endPoint.y;
Point newPoint = new Point(newX, newY);
Rectangle2D r2d = createRectangle(newPoint, radius);
Polygon polygon = boundary.getPolygon();
if (polygon.contains(r2d)) {
player.setCenter(newPoint);
panel.repaint();
}
originalPoint = null;
}
private Rectangle2D createRectangle(Point center, int radius) {
double dx = center.x - radius;
double dy = center.y - radius;
double d = radius + radius;
Rectangle2D r2d = new Rectangle2D.Double(dx, dy, d, d);
return r2d;
}
#Override
public void mouseEntered(MouseEvent event) {
}
#Override
public void mouseExited(MouseEvent event) {
}
}
public class Boundary {
private final Color color;
private final Polygon polygon;
public Boundary(Polygon polygon, Color color) {
this.polygon = polygon;
this.color = color;
}
public Polygon getPolygon() {
return polygon;
}
public Color getColor() {
return color;
}
}
public class Player {
private final int radius;
private final Color color;
private Point center;
public Player(int x, int y, int radius, Color color) {
this.center = new Point(x, y);
this.radius = radius;
this.color = color;
}
public int getRadius() {
return radius;
}
public Point getCenter() {
return center;
}
public void setCenter(Point center) {
this.center = center;
}
public Color getColor() {
return color;
}
}
}

I need help on moving the small box created to move smoothly as I click and drag near the outside layer. Here is my code: [duplicate]

I made a mini code that draw oval and link each other , now i try to move the oval(Circle) but I have a problem (in coding)
// Panneau.java
public class Panneau extends JPanel {
private int R = 20;
private boolean isDrag = false;
String text = "stack";
int x = 250, y = 200;
int height = 50, width = 50;
Random Rnd = new Random();
int rand=Rnd.nextInt();
int r=Math.abs(rand%250);
int r2=Math.abs(rand%250);
public Panneau() {
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if ((x<=e.getX() && x+R>=e.getX()) && ( y<=e.getY() && y+R>=e.getY())) {
moveVertex(e.getX(),e.getY());
isDrag = true;
}
}
#Override
public void mouseReleased(MouseEvent e) {
isDrag = false;
}
});
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
if (isDrag) moveVertex(e.getX(),e.getY());
}
});
}
private void moveVertex(int x1, int y1) {
if ((x!=x1) || (y!=y1)) {
x=x1-10;
y=y1-10;
repaint();
}
}
#Override
protected void paintComponent(Graphics g){
// declaration
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(x,y,x+r,y+r2);
g.setColor(Color.yellow);
g.fillOval(x-height/2, y-width/2,width, height);
g.fillOval((x-height/2)+r, (y-width/2)+r2,width, height);
FontMetrics fm = g.getFontMetrics();
double textWidth = fm.getStringBounds(text, g).getWidth();
g.setColor(Color.blue);
g.drawString(text, (int) (x - textWidth/2),(int) (y + fm.getMaxAscent() / 2));
g.drawString(text, (int) (x - textWidth/2)+r,(int) (y + fm.getMaxAscent() / 2)+r2);
}
}
I must move the two circles and the line must not move(Graph node)
please help me and thanks :)
After the update ( thanks to MadProgrammer) now I can move all the figure ( but if I clicked in the red circle only) , I want to move just circles thanks :)
Basically, because instead of using reapint(int, int) you could use repaint()
private void moveVertex(int x1, int y1) {
int OFFSET = 1;
if ((x != x1) || (y != y1)) {
x = x1 - 10;
y = y1 - 10;
repaint();
}
}
This will ensure that the entire component is repainted.
While I wouldn't discount the use of repaint(int, int), because your painting process is relatively simple, it's not going to provide you with a great deal of benefit at this stage
Updated with additional example
IF I understand, you want to be able to move a single node and have the line remain joined.
While it might be possible to implement within the code you have available, a simpler soltution would be to take advantage of the 2D Graphics Shape API, this provides a number of really useful functions, including determining of points fall within a given shape.
It also means you don't need to keep track of a large number of parameters, but instead, get a self contained object that just knows how it should be painted...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
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.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestGraphNode {
public static void main(String[] args) {
new TestGraphNode();
}
public TestGraphNode() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Panneau());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Panneau extends JPanel {
private int radius = 50;
private String text = "stack";
private List<Ellipse2D> nodes;
private Ellipse2D dragged;
private Point offset;
public Panneau() {
nodes = new ArrayList<>(25);
nodes.add(new Ellipse2D.Float(50 - (radius / 2), 100 - (radius / 2), radius, radius));
nodes.add(new Ellipse2D.Float(350 - (radius / 2), 100 - (radius / 2), radius, radius));
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
for (Ellipse2D node : nodes) {
if (node.contains(e.getPoint())) {
System.out.println("Clicked...");
dragged = node;
// Adjust for the different between the top/left corner of the
// node and the point it was clicked...
offset = new Point(node.getBounds().x - e.getX(), node.getBounds().y - e.getY());
// Highlight the clicked node
repaint();
break;
}
}
}
#Override
public void mouseReleased(MouseEvent e) {
// Erase the "click" highlight
if (dragged != null) {
repaint();
}
dragged = null;
offset = null;
}
});
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
if (dragged != null && offset != null) {
// Adjust the position of the drag point to allow for the
// click point offset
Point to = e.getPoint();
to.x += offset.x;
to.y += offset.y;
// Modify the position of the node...
Rectangle bounds = dragged.getBounds();
bounds.setLocation(to);
dragged.setFrame(bounds);
// repaint...
repaint();
}
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
// declaration
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
// Draw the connecting lines first
// This ensures that the lines are under the nodes...
Point p = null;
for (Ellipse2D node : nodes) {
g2d.setColor(Color.BLACK);
Point to = node.getBounds().getLocation();
to.x += radius / 2;
to.y += radius / 2;
if (p != null) {
g2d.draw(new Line2D.Float(p, to));
}
p = to;
}
// Draw the nodes...
for (Ellipse2D node : nodes) {
g2d.setColor(Color.yellow);
g2d.fill(node);
if (node == dragged) {
g2d.setColor(Color.BLUE);
g2d.draw(node);
}
g2d.setColor(Color.BLUE);
FontMetrics fm = g.getFontMetrics();
int textWidth = fm.stringWidth(text);
int x = node.getBounds().x;
int y = node.getBounds().y;
int width = node.getBounds().width;
int height = node.getBounds().height;
g.drawString(text,
x + ((width - textWidth)) / 2,
y + ((height - fm.getHeight()) / 2) + fm.getAscent());
}
g2d.dispose();
}
}
}

I want to drag one object at a time but this code drags both the objects at a time

I want to drag one object at a time but this code drags both the objects at a time
package javaPgm;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.Graphics.*;
public class Drag extends Applet
implements MouseListener, MouseMotionListener {
int width, height;
int x, y; // coordinates of upper left corner of the box
int mx, my; // the most recently recorded mouse coordinates
boolean isMouseDraggingBox = false;
public void init() {
width = getSize().width;
height = getSize().height;
x = width/2 - 20;
y = height/2 - 20;
addMouseListener( this );
addMouseMotionListener( this );
}
public void mouseEntered( MouseEvent e ) { }
public void mouseExited( MouseEvent e ) { }
public void mouseClicked( MouseEvent e ) { }
public void mousePressed( MouseEvent e ) {
mx = e.getX();
my = e.getY();
if ( x < mx && mx < x+40 && y < my && my < y+40 ) {
isMouseDraggingBox = true;
}
e.consume();// consumes the current event
}
public void mouseReleased( MouseEvent e ) {
isMouseDraggingBox = false;
e.consume();
}
public void mouseMoved( MouseEvent e ) { }
public void mouseDragged( MouseEvent e ) {
if ( isMouseDraggingBox ) {
int new_mx = e.getX();
int new_my = e.getY();
x += new_mx - mx;
y += new_my - my;
mx = new_mx;
my = new_my;
repaint();
e.consume();
}
}
public void paint( Graphics g ) {
g.drawRect( 20, 40, 50, 85 );
g.drawString("circle",20 , 38);
Font f = new Font("TimesRoman", Font.PLAIN, 20);// to set font style and size
g.setFont(f);
g.drawString("RED=Positive charge", 175, 188);// to write a text
g.drawString("BLUE=negative charge", 199, 210);
g.drawRect(100,140,60,85);
g.setColor(Color.red);
g.fillOval(x,y,15,15);
g.setColor(Color.blue);
g.fillOval(x-110,y-135,15,15);
setBackground(Color.yellow);
for(int i=0;i<=950;i+=30){// to draw horizontal and vertical lines
g.setColor(Color.orange);
g.drawLine(i,0,i,950);
}
for(int j=0;j<=950;j+=30){
g.drawLine(0, j, 950, j);
}
}
}
The first thing you need is some way to tell the difference between your "objects".
The next thing you need is some way to reference this objects in a convenient method. You could use an array, but I'm lazy and prefer to use a List
Once you have these two things, painting the boxes is just a matter of looping through the List and determining which object was clicked is becomes basically the same process...
To that end, I wrapped a java.awt.Rectangle around a custom Box class, which also maintains color information, this makes it much easier to manage as Rectangle has some very useful methods and can be painted easily.
import java.awt.Color;
import java.awt.Dimension;
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.util.ArrayList;
import java.util.List;
import javax.swing.JApplet;
import javax.swing.JPanel;
public class WhatADag extends JApplet {
#Override
public void init() {
add(new DragPane());
}
public class DragPane extends JPanel {
private List<Box> boxes;
public DragPane() {
boxes = new ArrayList<>(25);
boxes.add(new Box(0, 0, 50, 50, Color.RED));
boxes.add(new Box(150, 150, 50, 50, Color.BLUE));
MouseAdapter handler = new MouseAdapter() {
private Box hitBox;
private Point offset;
#Override
public void mousePressed(MouseEvent e) {
Point mp = e.getPoint();
for (Box box : boxes) {
if (box.getBounds().contains(mp)) {
hitBox = box;
offset = new Point();
offset.x = mp.x - box.getBounds().x;
offset.y = mp.y - box.getBounds().y;
}
}
}
#Override
public void mouseReleased(MouseEvent e) {
hitBox = null;
}
#Override
public void mouseDragged(MouseEvent e) {
if (hitBox != null) {
Point mp = e.getPoint();
Rectangle bounds = hitBox.getBounds();
bounds.x = mp.x - offset.x;
bounds.y = mp.y - offset.y;
repaint();
}
}
};
addMouseListener(handler);
addMouseMotionListener(handler);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (Box rect : boxes) {
g2d.setColor(rect.getColor());
g2d.fill(rect.getBounds());
}
g2d.dispose();
}
}
public class Box {
private Color color;
private Rectangle rectangle;
public Box(int x, int y, int width, int height, Color color) {
rectangle = new Rectangle(x, y, width, height);
setColor(color);
}
public void setColor(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
public Rectangle getBounds() {
return rectangle;
}
}
}
Take a look at Performing Custom Painting and 2D Graphics for more details

Letting user draw a rectangle with mouse in Java

I'm writing a program that lets the user draw a hollow rectangle on the screen on top of an image. They can also click on the image and the clicks are joined up to form polygons.
Joining up points works fine, but when the user drags to draw a rectangle, the previously drawn rectangles and polygons disappear. The runnable code is below;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageLabeller extends JFrame {
static boolean drawRectangle = false;
/**
* some java stuff to get rid of warnings
*/
private static final long serialVersionUID = 1L;
/**
* main window panel
*/
JPanel appPanel = null;
/**
* toolbox - put all buttons here
*/
JPanel toolboxPanel = null;
/**
* image panel - displays image and editing area
*/
static ImagePanel imagePanel;
/**
* handles New Object button action
*/
public ImageLabeller(String imageFilename) {
try {
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
System.out.println("Bye bye!");
System.exit(0);
}
});
// Create and set up the image panel.
// setup main window panel
setExtendedState(Frame.MAXIMIZED_BOTH);
appPanel = new JPanel();
appPanel.setLayout(new BoxLayout(appPanel, BoxLayout.Y_AXIS));
this.setContentPane(appPanel);
imagePanel = new ImagePanel(imageFilename);
imagePanel.setOpaque(true); // content panes must be opaque
imagePanel.setBorder(BorderFactory.createLineBorder(Color.green));
// create toolbox panel
toolboxPanel = new JPanel();
toolboxPanel.setBorder(BorderFactory.createLineBorder(Color.black));
JButton newPolyButton = new JButton("New object");
newPolyButton.setMnemonic(KeyEvent.VK_N);
// newPolyButton.setSize(50, 20);
newPolyButton.setToolTipText("Click to add new object");
newPolyButton.addActionListener(new DrawListener());
JButton newSquareButton = new JButton("New Square");
newSquareButton.setMnemonic(KeyEvent.VK_S);
// newPolyButton.setSize(50, 20);
newSquareButton.setEnabled(true);
newSquareButton.setToolTipText("Click to add new square");
newSquareButton.addActionListener(new SquareListener());
// add all buttons to toolboxPanel
toolboxPanel.add(newPolyButton);
toolboxPanel.add(newSquareButton);
// add all panels to appPanel
appPanel.add(toolboxPanel);
appPanel.add(imagePanel);
// appPanel.add(Box.createRigidArea(new Dimension(0,10)));
// display all the stuff
this.pack();
this.setVisible(true);
} catch (Exception e) {
System.err.println("Image: ");
e.printStackTrace();
}
}
public static void addNewPolygon() {
imagePanel.addNewPolygon();
}
public static void addNewRectangle() {
//imagePanel.addNewRectangle();
}
static class DrawListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
addNewPolygon();
}
}
static class SquareListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
drawRectangle = true;
imagePanel.drawingRectangle = true;
System.out.println(imagePanel.drawingRectangle);
}
}
public static void main (String args []) {
new ImageLabeller("/change to/a photo/ of your choice.jpg");
}
}
_
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel implements MouseListener,
MouseMotionListener {
Rectangle currentRectangle = null;
boolean drawingRectangle = false;
/**
* some java stuff to get rid of warnings
*/
private static final long serialVersionUID = 1L;
/**
* image to be tagged
*/
BufferedImage image = null;
/**
* list of current polygon's vertices
*/
ArrayList<Point> currentPolygon = null;
/**
* list of polygons
*/
ArrayList<ArrayList<Point>> polygonsList = null;
ArrayList<Rectangle> rectangleList = null;
/**
* extended constructor - loads image to be labelled
*
* #param imageName
* - path to image
* #throws Exception
* if error loading the image
*/
public ImagePanel(String imageName) throws Exception {
currentPolygon = new ArrayList<Point>();
polygonsList = new ArrayList<ArrayList<Point>>();
rectangleList = new ArrayList<Rectangle>();
image = ImageIO.read(new File(imageName));
Dimension panelSize = new Dimension(image.getWidth(), image.getHeight());
this.setSize(panelSize);
this.setMinimumSize(panelSize);
this.setPreferredSize(panelSize);
this.setMaximumSize(panelSize);
setBounds(0, 0, image.getWidth(), image.getHeight());
addMouseListener(this);
addMouseMotionListener(this);
this.setVisible(true);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("Paint Component");
Graphics2D g2d = (Graphics2D) g;
// Paint image on screen
g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
// display all the completed polygons
for (ArrayList<Point> polygon : polygonsList) {
drawPolygon(polygon);
finishPolygon(polygon);
System.out.println("Polly");
}
// Display all completed squares
for (Rectangle r : rectangleList) {
drawRectangle(r);
System.out.println("Square");
}
// display current polygon
if (currentPolygon != null) {
drawPolygon(currentPolygon);
}
// display current square
if (currentRectangle != null) {
drawRectangle(currentRectangle);
}
}
/**
* displays a polygon without last stroke
*
* #param polygon
* to be displayed
*/
public void drawPolygon(ArrayList<Point> polygon) {
Graphics2D g = (Graphics2D) this.getGraphics();
// set to red so I can see when it's being redrawn
g.setColor(Color.RED);
g.setStroke(new BasicStroke(3));
for (int i = 0; i < polygon.size(); i++) {
Point currentVertex = polygon.get(i);
if (i != 0) {
Point prevVertex = polygon.get(i - 1);
g.drawLine(prevVertex.getX(), prevVertex.getY(),
currentVertex.getX(), currentVertex.getY());
}
g.fillOval(currentVertex.getX() - 5, currentVertex.getY() - 5, 10,
10);
}
}
public void drawRectangle(Rectangle r) {
Graphics2D g = (Graphics2D) this.getGraphics();
g.setStroke(new BasicStroke(3));
g.setColor(Color.BLUE);
g.drawLine(r.getX1(), r.getY1(), r.getX2(), r.getY1());
g.drawLine(r.getX1(), r.getY1(), r.getX1(), r.getY2());
g.drawLine(r.getX2(), r.getY2(), r.getX2(), r.getY1());
g.drawLine(r.getX2(), r.getY2(), r.getX1(), r.getY2());
System.out.println(r.getX1() + " " + r.getY1() + " " + r.getX2());
System.out.println("Drawn rectangle");
}
/**
* displays last stroke of the polygon (arch between the last and first
* vertices)
*
* #param polygon
* to be finished
*/
public void finishPolygon(ArrayList<Point> polygon) {
// if there are less than 3 vertices than nothing to be completed
if (polygon.size() >= 3) {
Point firstVertex = polygon.get(0);
Point lastVertex = polygon.get(polygon.size() - 1);
Graphics2D g = (Graphics2D) this.getGraphics();
g.setColor(Color.GREEN);
g.setStroke(new BasicStroke(3));
g.drawLine(firstVertex.getX(), firstVertex.getY(),
lastVertex.getX(), lastVertex.getY());
}
}
/**
* moves current polygon to the list of polygons and makes pace for a new
* one
*/
public void addNewPolygon() {
// finish the current polygon if any
if (currentPolygon != null) {
finishPolygon(currentPolygon);
polygonsList.add(currentPolygon);
}
currentPolygon = new ArrayList<Point>();
}
public void mouseClicked(MouseEvent e) {
if (!drawingRectangle) {
int x = e.getX();
int y = e.getY();
// check if the cursor is within image area
if (x > image.getWidth() || y > image.getHeight()) {
// if not do nothing
return;
}
Graphics2D g = (Graphics2D) this.getGraphics();
// if the left button than we will add a vertex to poly
if (e.getButton() == MouseEvent.BUTTON1) {
g.setColor(Color.GREEN);
if (currentPolygon.size() != 0) {
Point lastVertex = currentPolygon
.get(currentPolygon.size() - 1);
g.setStroke(new BasicStroke(3));
g.drawLine(lastVertex.getX(), lastVertex.getY(), x, y);
}
g.fillOval(x - 5, y - 5, 10, 10);
currentPolygon.add(new Point(x, y));
System.out.println(x + " " + y + " polygon point");
}
}
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
if (drawingRectangle) {
currentRectangle = new Rectangle(arg0.getX(), arg0.getY(),
arg0.getX(), arg0.getY(), Color.BLACK);
}
}
public void mouseReleased(MouseEvent arg0) {
if (drawingRectangle) {
rectangleList.add(new Rectangle(currentRectangle.getX1(),
currentRectangle.getY1(), arg0.getX(), arg0.getY(),
currentRectangle.getColor()));
System.out.println(currentRectangle.getX1() + " "
+ currentRectangle.getY1() + " " + arg0.getX() + " "
+ arg0.getY() + " rectangle point");
// unnecessary when mouseDragged calls paintComponent directly?
drawRectangle(new Rectangle(currentRectangle.getX1(),
currentRectangle.getY1(), arg0.getX(), arg0.getY(),
currentRectangle.getColor()));
currentRectangle = null;
drawingRectangle = false;
}
}
public void mouseDragged(MouseEvent arg0) {
if (drawingRectangle) {
currentRectangle = new Rectangle(currentRectangle.getX1(),
currentRectangle.getY1(), arg0.getX(), arg0.getY(),
currentRectangle.getColor());
System.out.println(currentRectangle.getX1() + " "
+ currentRectangle.getY1() + " " + arg0.getX() + " "
+ arg0.getX() + " " + "Dragging");
repaint();
// It works better using this instead on repaint()
// Graphics g = this.getGraphics();
// paintComponent(g);
}
}
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
-
public class Point {
private int x = 0;
private int y = 0;
public Point() {
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
-
import java.awt.Color;
import java.awt.Graphics2D;
public class Rectangle {
// Initialize variables
private int x1; // x coordinate of first endpoint
private int y1; // y coordinate of first endpoint
private int x2; // x coordinate of second endpoint
private int y2; // y coordinate of second endpoint
private Color colour; // colour of the shape
// A no-parameter constructor that sets all the coordinates of the shape to
// 0 and the
// colour to Color.BLACK
public Rectangle() {
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
colour = Color.BLACK;
}
// A constructor that initializes the coordinates and colour to the values
// of the
// parameters supplied.
public Rectangle(int x1, int y1, int x2, int y2, Color col) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.colour = col;
}
public void setX1(int x1) {
this.x1 = x1;
}
public void setY1(int y1) {
this.y1 = y1;
}
public void setX2(int x2) {
this.x2 = x2;
}
public void setY2(int y2) {
this.y2 = y2;
}
public void setColor(Color colour) {
this.colour = colour;
}
public int getX1() {
return this.x1;
}
public int getY1() {
return this.y1;
}
public int getX2() {
return this.x2;
}
public int getY2() {
return this.y2;
}
public Color getColor() {
return this.colour;
}
public int getWidth() {
return (Math.abs(x2 - x1));
}
public int getHeight() {
return (Math.abs(y2 - y1));
}
public int getUpperLeftX() {
return (Math.min(x1, x2));
}
public int getUpperLeftY() {
return (Math.min(y1, y2));
}
}
Sorry for the mass of code, I tried to trim out as much as I could.
Clicking on the image draws points which are joined up to create lines. When the user clicks the "New Object" button, the first and last points are joined to create a polygon. This all works fine, but if you click "New Square" and drag on the image, all previous shapes flicker as the mouse is moved and disappear when the mouse button is released. If "New Square" is clicked again (a necessity of poor coding on my behalf so far) and another square drawn, the 'disappeared' shapes can be seen flickering again, but then disappear once the mouse is released.
I'm calling repaint() in the mouseDragged(...) event, which I thought was all that was necessary. It actually works (almost) as wanted when I change
repaint();
for
Graphics g = this.getGraphics();
paintComponent(g);
but every book and article I've read said I should never call paintComponent myself, ever. An issue with calling paintComponent however is that the background image tends to flicker alot.
If repaint() calls paintComponent, why do they lead to different results?
I also don't understand why, when using repaint() in the mouseDragged event, I must , I must also call drawRectangle(...) in mouseReleased for the square to be seen at all, but when using paintComponent, I don't?
Any advice or pointers are greatly appreciated, thankyou.
In your drawRectangle and drawPolygon you are re-getting a graphics object, but you are calling them from paintComponent. this is what's causing the odd behaviour, you should pass the graphics from painComponent in to those methods.
I am seeing other odd behaviour though, like the polygons stay green until I've finished painting a square, when they then turn red, but one of the lines stays green and eventually vanishes. I didn't look in to that too much.
Also, polygon drawing and Point and Rectangle are supported in awt, is there any reason you chose to create your own classes for those?
package test;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel implements MouseListener,
MouseMotionListener {
Rectangle currentRectangle = null;
boolean drawingRectangle = false;
/**
* some java stuff to get rid of warnings
*/
private static final long serialVersionUID = 1L;
/**
* image to be tagged
*/
BufferedImage image = null;
/**
* list of current polygon's vertices
*/
ArrayList<Point> currentPolygon = null;
/**
* list of polygons
*/
ArrayList<ArrayList<Point>> polygonsList = null;
ArrayList<Rectangle> rectangleList = null;
/**
* extended constructor - loads image to be labelled
*
* #param imageName
* - path to image
* #throws Exception
* if error loading the image
*/
public ImagePanel(String imageName) throws Exception {
currentPolygon = new ArrayList<Point>();
polygonsList = new ArrayList<ArrayList<Point>>();
rectangleList = new ArrayList<Rectangle>();
image = ImageIO.read(new File(imageName));
Dimension panelSize = new Dimension(image.getWidth(), image.getHeight());
this.setSize(panelSize);
this.setMinimumSize(panelSize);
this.setPreferredSize(panelSize);
this.setMaximumSize(panelSize);
setBounds(0, 0, image.getWidth(), image.getHeight());
addMouseListener(this);
addMouseMotionListener(this);
this.setVisible(true);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("Paint Component");
Graphics2D g2d = (Graphics2D) g;
// Paint image on screen
g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
// display all the completed polygons
for (ArrayList<Point> polygon : polygonsList) {
drawPolygon(polygon,g);
finishPolygon(polygon);
System.out.println("Polly");
}
// Display all completed squares
for (Rectangle r : rectangleList) {
drawRectangle(r,g);
System.out.println("Square");
}
// display current polygon
if (currentPolygon != null) {
drawPolygon(currentPolygon, g);
}
// display current square
if (currentRectangle != null) {
drawRectangle(currentRectangle, g);
}
}
/**
* displays a polygon without last stroke
*
* #param polygon
* to be displayed
*/
public void drawPolygon(ArrayList<Point> polygon, Graphics gr) {
Graphics2D g = null;
if (gr instanceof Graphics2D) {
g = (Graphics2D) gr;
}
else{ return; }
// set to red so I can see when it's being redrawn
g.setColor(Color.RED);
g.setStroke(new BasicStroke(3));
for (int i = 0; i < polygon.size(); i++) {
Point currentVertex = polygon.get(i);
if (i != 0) {
Point prevVertex = polygon.get(i - 1);
g.drawLine(prevVertex.getX(), prevVertex.getY(),
currentVertex.getX(), currentVertex.getY());
}
g.fillOval(currentVertex.getX() - 5, currentVertex.getY() - 5, 10,
10);
}
}
public void drawRectangle(Rectangle r, Graphics gr) {
Graphics2D g = null;
if (gr instanceof Graphics2D) {
g = (Graphics2D) gr;
}
else{ return; }
g.setStroke(new BasicStroke(3));
g.setColor(Color.BLUE);
g.drawLine(r.getX1(), r.getY1(), r.getX2(), r.getY1());
g.drawLine(r.getX1(), r.getY1(), r.getX1(), r.getY2());
g.drawLine(r.getX2(), r.getY2(), r.getX2(), r.getY1());
g.drawLine(r.getX2(), r.getY2(), r.getX1(), r.getY2());
System.out.println(r.getX1() + " " + r.getY1() + " " + r.getX2());
System.out.println("Drawn rectangle");
}
/**
* displays last stroke of the polygon (arch between the last and first
* vertices)
*
* #param polygon
* to be finished
*/
public void finishPolygon(ArrayList<Point> polygon) {
// if there are less than 3 vertices than nothing to be completed
if (polygon.size() >= 3) {
Point firstVertex = polygon.get(0);
Point lastVertex = polygon.get(polygon.size() - 1);
Graphics2D g = (Graphics2D) this.getGraphics();
g.setColor(Color.GREEN);
g.setStroke(new BasicStroke(3));
g.drawLine(firstVertex.getX(), firstVertex.getY(),
lastVertex.getX(), lastVertex.getY());
}
}
/**
* moves current polygon to the list of polygons and makes pace for a new
* one
*/
public void addNewPolygon() {
// finish the current polygon if any
if (currentPolygon != null) {
finishPolygon(currentPolygon);
polygonsList.add(currentPolygon);
}
currentPolygon = new ArrayList<Point>();
}
public void mouseClicked(MouseEvent e) {
if (!drawingRectangle) {
int x = e.getX();
int y = e.getY();
// check if the cursor is within image area
if (x > image.getWidth() || y > image.getHeight()) {
// if not do nothing
return;
}
Graphics2D g = (Graphics2D) this.getGraphics();
// if the left button than we will add a vertex to poly
if (e.getButton() == MouseEvent.BUTTON1) {
g.setColor(Color.GREEN);
if (currentPolygon.size() != 0) {
Point lastVertex = currentPolygon
.get(currentPolygon.size() - 1);
g.setStroke(new BasicStroke(3));
g.drawLine(lastVertex.getX(), lastVertex.getY(), x, y);
}
g.fillOval(x - 5, y - 5, 10, 10);
currentPolygon.add(new Point(x, y));
System.out.println(x + " " + y + " polygon point");
}
}
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
if (drawingRectangle) {
currentRectangle = new Rectangle(arg0.getX(), arg0.getY(),
arg0.getX(), arg0.getY(), Color.BLACK);
}
}
public void mouseReleased(MouseEvent arg0) {
if (drawingRectangle) {
rectangleList.add(new Rectangle(currentRectangle.getX1(),
currentRectangle.getY1(), arg0.getX(), arg0.getY(),
currentRectangle.getColor()));
System.out.println(currentRectangle.getX1() + " "
+ currentRectangle.getY1() + " " + arg0.getX() + " "
+ arg0.getY() + " rectangle point");
// unnecessary when mouseDragged calls paintComponent directly?
/*drawRectangle(new Rectangle(currentRectangle.getX1(),
currentRectangle.getY1(), arg0.getX(), arg0.getY(),
currentRectangle.getColor()));*/
currentRectangle = null;
drawingRectangle = false;
}
}
public void mouseDragged(MouseEvent arg0) {
if (drawingRectangle) {
currentRectangle = new Rectangle(currentRectangle.getX1(),
currentRectangle.getY1(), arg0.getX(), arg0.getY(),
currentRectangle.getColor());
System.out.println(currentRectangle.getX1() + " "
+ currentRectangle.getY1() + " " + arg0.getX() + " "
+ arg0.getX() + " " + "Dragging");
repaint();
// It works better using this instead on repaint()
// Graphics g = this.getGraphics();
// paintComponent(g);
}
}
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}

Categories