I need to write a program for drawing concentric squares.
Program with the first click of the mouse determines the x and y coordinate of first corner of the square. Then, the mouse moves and the second click determines the point of the opposite corner. I wrote the first part of a program that draws squares, and I began the second part, which should with the help of the mouse draw this drawing. I do not know in particular to use mouse listeners, so please help me.
I also used acm.jar because these packages are more familiar to me, but it can be done with the standard packages.
It shoud look like this (number of squares is not important):
http://th02.deviantart.net/fs71/150/f/2011/063/a/a/square_target_24_by_10binary-d3axgdh.png
First part of program:
import acm.graphics.*;
public class ConcentricniKvadrati extends GCompound {
private static final double PRVI_KVADRAT = 0.80;
private static final double DRUGI_KVADRAT = 0.60;
private static final double TRECI_KVADRAT = 0.40;
private static final double CETVRTI_KVADRAT = 0.20;
private GRect Nulti;
private GRect Prvi;
private GRect Drugi;
private GRect Treci;
private GRect Cetvrti;
public ConcentricniKvadrati (double width, double heigth) {
Nulti = new GRect(width, heigth);
Prvi = new GRect(width*PRVI_KVADRAT, heigth*PRVI_KVADRAT);
Drugi = new GRect(width*DRUGI_KVADRAT, heigth*DRUGI_KVADRAT);
Treci = new GRect(width*TRECI_KVADRAT, heigth*TRECI_KVADRAT);
Cetvrti = new GRect(width*CETVRTI_KVADRAT, heigth*CETVRTI_KVADRAT);
add(Nulti, 0, 0);
add(Prvi, width*0.10, heigth*0.10);
add(Drugi, width*0.20, heigth*0.20);
add(Treci, width*0.30, heigth*0.30);
add(Cetvrti, width*0.40, heigth*0.40);
}
}
Second part:
import acm.program.*;
import java.awt.event.*;
public class Crtanje extends GraphicsProgram {
public void init() {
addMouseListeners();
}
public void mousePressed(MouseEvent me) {
originalX = me.getX();
originalY = me.getY();
ConcentricniKvadrati kvadrat = new ConcentricniKvadrati (WIDTH, HEIGHT);
add(kvadrat);
}
public void mouseDragged(MouseEvent me) {
kvadrat.setSize(Math.abs(me.getX() - originalX), Math.abs( me.getY() - originalY));
kvadrat.setLocation(Math.min(me.getX(), originalX), Math.min( me.getY(), originalY));
}
private ConcentricniKvadrati kvadrat;
private int originalX;
private int originalY;
}