我有一个愚蠢的错误,我无法在用 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);
}
最佳答案
您必须将 X1 与 X2 以及 Y1 与 Y2 进行比较,如果 *1 > *2 - 将它们交换为 drawRect()。
关于java - 自制油漆应用程序中的绘图错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27379987/