如何使用 swing 在 Java 中绘制倒矩形?
使用“g.drawRect(x,y,width,height)”方法, 通过鼠标拖动创建矩形成功,但是出现了一个小错误。
如果拖动到比第一个点(x,y)大的点(x2,y2| x2>x1 && y2>y1),它将正常运行。
但是,在相反的情况下,如果拖动点的坐标小于第一个单击点的坐标,则按相反方向绘制,而不是向拖动点方向绘制。
即使我尝试通过 if() 反转它,我也不知道该怎么做。
我想要的方向就像Window中的一个拖动框,但这对我来说有点困难。 请给我一些提示来克服这次艰难的旅程。
↓这是我的代码
class Rect {
int x, y, w, h;
}
public class Rectangle extends JPanel{
int i = 0;
int x, y = 0;
Rect [] ary = new Rect[100];
public Rectangle() {
addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
if(i>100) return;
ary[i] = new Rect();
ary[i].x = e.getX(); ary[i].y = e.getY();
x= ary[i].x; y = ary[i].y;
}
@Override
public void mouseReleased(MouseEvent e) {
ary[i].w = Math.abs(ary[i].x-e.getX());
ary[i].h = Math.abs(ary[i].y- e.getY());
i++;
repaint();
}
});
addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
ary[i].w = Math.abs(ary[i].x-e.getX());
ary[i].h = Math.abs(ary[i].y- e.getY());
repaint();
}
public void mouseMoved(MouseEvent e) {
}
});
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(Rect r:ary){
if(r !=null) {
g.setColor(Color.BLACK);
g.drawRect(r.x, r.y, r.w, r.h);
}
}
}
}
请帮帮我
最佳答案
首先不要使用数组来存储要绘制的矩形对象。使用 ArrayList,当您想要绘制更多矩形时,它会动态增长。
当前代码的问题是您尝试用 3 个单独的方法更新 x/y/宽度/高度值。这只能在 mouseDragged
方法中完成。
基本步骤是:
- 在
mousePressed
中,您保存初始鼠标点。创建一个空的 Rectangle 对象用于绘制矩形 - 在
mouseDragged
中,您将初始鼠标点与当前鼠标点进行比较,并确定最小 x/y 值。然后,您分别获得 x 和 y 值的绝对值,以便了解矩形的宽度/高度。更新矩形对象的 x/y/宽度/高度值并重新绘制矩形 - 在
mouseReleased
中,将 Rectangle 对象添加到 ArrayList
请参阅 Custom Painting Approaches 中的 DrawOnComponent
示例获取实现上述建议的工作示例。
上面示例中的 MouseInputAdapter 实现如下。它显示了 mouseDragged 方法中的大部分逻辑:
class MyMouseListener extends MouseInputAdapter
{
private Point startPoint;
public void mousePressed(MouseEvent e)
{
startPoint = e.getPoint();
shape = new Rectangle();
}
public void mouseDragged(MouseEvent e)
{
int x = Math.min(startPoint.x, e.getX());
int y = Math.min(startPoint.y, e.getY());
int width = Math.abs(startPoint.x - e.getX());
int height = Math.abs(startPoint.y - e.getY());
shape.setBounds(x, y, width, height);
repaint();
}
public void mouseReleased(MouseEvent e)
{
if (shape.width != 0 || shape.height != 0)
{
addRectangle(shape, e.getComponent().getForeground());
}
shape = null;
}
}
关于java - 如何通过鼠标拖动绘制一个倒置的正方形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53371072/