I have a stupid bug i cant figure out in the Paint-like application developed in Java. My problem is now that when i draw shapes (let say rectangles) the rectangle should be drawing in all 4 directions (whatever way is dragged), but now its drawing only in the down-right direction. I coded it to be all directions. While figuring out the error i realized that when you drag up-left the initial x and y take value of the x2, y2. I have no idea why its happening as i have no code that is doing that. Please help, I ve been on this bug all night ((
this class is responsible for all the shapes
public abstract class DrawShapes implements DrawListenerInterface {
private final Canvas canvas;
protected int x;
protected int y;
protected int x2;
protected int y2;
protected int w;
private boolean prev;
protected int h;
public DrawShapes(Canvas canvas) {
this.canvas = canvas;
}
@Override
public void preview(Graphics2D g2) {
g2.setColor(Color.black);
if (prev) {
draw(g2);
}
}
@Override
public void draw(Graphics2D g2) {
System.out.println("before " + x + " " + y + " " + x2 + " " + y2);
x = Math.min(x, x2);
y = Math.min(y, y2);
w = Math.abs(x - x2);
h = Math.abs(y - y2);
//
System.out.println("after " + x + " " + y + " " + x2 + " " + y2);
}
@Override
public void mousePressed(MouseEvent e) {
prev = true;
this.x = e.getX();
this.y = e.getY();
this.x2 = e.getX();
this.y2 = e.getY();
System.out.println("PRESSED " + x + " " + x2 + " " + y + " " + y2);
canvas.repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
// this.x2 = e.getX();
// this.y2 = e.getY();
final Graphics2D g2 = (Graphics2D) canvas.getImage().getGraphics();
canvas.defaultSettings(g2);
prev = false;
draw(g2);
// canvas.repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
this.x2 = e.getX();
this.y2 = e.getY();
System.out.println("dragging " + x2 + " " + y2);
this.canvas.repaint();
}
this class is the child class of DrawShapes that is drawing its own shape
public class SquareListener extends DrawShapes {
@Override
public void draw(Graphics2D g2) {
// TODO Auto-generated method stub
super.draw(g2);
g2.drawRect(x, y, w, h);
// System.out.println(x + " " + y + " " + x2 + " " + y2);
}
您必须将X1与X2和Y1与Y2进行比较,以防万一* 1> * 2-将它们交换为drawRect()。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.