gpt4 book ai didi

java - 如何在Java中放大/移动多边形?

转载 作者:行者123 更新时间:2023-12-01 14:53:42 24 4
gpt4 key购买 nike

所以我有以下代码:

import java.awt.*;

public class Triangle extends Point {
protected int size;
private int p1x, p2x, p3x, p1y, p2y, p3y;

//Create a new triangle
public Triangle()
{
super();
size = 100;
yPos = 100;
}


public void reSize(int newSize) {
size = size + newSize;
}

//Draw the triangle with current specifications on screen.
public void display(Graphics g) {
p1x = (size / 3);
p2x = (size / 2);
p3x = ((2 * size) / 3);
p1y = ((2 * size) / 3);
p2y = (size / 3);
p3y = ((2 * size) / 3);
int[] xPoints = { p1x, p2x, p3x };
int[] yPoints = { p1y, p2y, p3y };
int npoints = 3;
g.fillPolygon(xPoints, yPoints, npoints);
}
}

下面的代码用于放大/缩小三角形:

    if (e.getSource() == makeBigger) {
aShape.reSize(20);
}

else if (e.getSource() == makeSmaller) {
aShape.reSize(-20);
}

问题是,我还希望能够使用以下代码拖动它:

    this.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
shapeColor = Color.black;
repaint();
}

public void mouseDragged(MouseEvent me) {
shapeColor = Color.lightGray;
aShape.moveXY(me.getX(), me.getY());
repaint();
}
});

this.addMouseMotionListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
shapeColor = Color.black;
repaint();
}

public void mouseDragged(MouseEvent me) {
shapeColor = Color.lightGray;
aShape.moveXY(me.getX(), me.getY());
repaint();
}
});

我能看到它的唯一方法是我可以选择其中之一。我如何将其结合起来才能拥有这两种功能?目前它可以完美地调整大小,但是假设我将 x/y 坐标中的变量大小更改为 yPos/xPos,我将能够拖动三角形但无法 reshape 它的形状。

谢谢!

最佳答案

您需要添加 xOffsetyOffset 成员,并在计算角点时添加它们:

public class Triangle extends Point {
protected int size;
private int p1x, p2x, p3x, p1y, p2y, p3y;
private int xOffset=0;
private int yOffset=0;

// ...

//Draw the triangle with current specifications on screen.
public void display(Graphics g) {
p1x = (size / 3) + xOffset;
p2x = (size / 2) + xOffset;
p3x = ((2 * size) / 3) + xOffset;
p1y = ((2 * size) / 3) + yOffset;
p2y = (size / 3) + yOffset;
p3y = ((2 * size) / 3) + yOffset;
int[] xPoints = { p1x, p2x, p3x };
int[] yPoints = { p1y, p2y, p3y };
int npoints = 3;
g.fillPolygon(xPoints, yPoints, npoints);
}

public void moveXY(int deltaX, int deltaY) {
xOffset += deltaX;
yOffset += deltaY;
}
}

这应该可以让您平移多边形。但请注意,上述 moveXY 方法期望参数包含与之前的差异,而不是绝对位置。如果您想要一个绝对位置,这很容易实现,并且可以作为练习。 ;)

关于java - 如何在Java中放大/移动多边形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14528124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com