所以我有以下代码:
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我将能够拖动三角形而不是重塑它。
谢谢!
答案 0 :(得分:1)
您希望添加xOffset
和yOffset
成员,并在计算角点时添加这些成员:
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
方法需要包含差异的参数,而不是绝对位置。如果你想要一个绝对的位置,这很容易实现并留下作为练习。 ;)