在自制油漆应用中绘制bug

时间:2014-12-09 13:23:39

标签: java graphics

我有一个愚蠢的错误,我无法弄清楚用Java开发的类似Paint的应用程序。我现在的问题是,当我绘制形状(比如说矩形)时,矩形应该在所有4个方向上绘制(无论是什么方式被拖动),但现在它只在右下方向绘制。我将它编码为所有方向。在弄清楚错误时我意识到当你向上拖动时,初始x和y取x2,y2的值。我不知道它为什么会发生,因为我没有这样做的代码。请帮忙,我整晚都在讨论这个问题((

这个班负责所有形状

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();

}

此类是DrawShapes的子类,它绘制自己的形状

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);
}

1 个答案:

答案 0 :(得分:1)

你必须将X1与X2和Y1与Y2进行比较,如果是* 1> * 2 - 将它们换成drawRect()。