1
我想中心一個現有的三角形。提示要求三角形的底部是畫布的長度,並且峯頂接觸頂部和居中。這是一個班級,代碼給了。如何在Java中居中圖像?
public class Triangle {
private int height;
private int width;
private int xPosition;
private int yPosition;
private String color;
private boolean isVisible;
public Triangle() {
height = 270;
width = 270;
xPosition = 120;
yPosition = 120;
color = "green";
isVisible = false;
}
public void makeVisible() {
isVisible = true;
draw();
}
public void makeInvisible() {
erase();
isVisible = false;
}
public void moveRight() {
moveHorizontal(20);
}
public void moveLeft() {
moveHorizontal(-20);
}
public void moveUp() {
moveVertical(-20);
}
public void moveDown() {
moveVertical(20);
}
public void moveHorizontal(int distance) {
erase();
xPosition += distance;
draw();
}
public void moveVertical(int distance) {
erase();
yPosition += distance;
draw();
}
public void slowMoveHorizontal(int distance) {
int delta;
if(distance < 0) {
delta = -1;
distance = -distance;
}
else {
delta = 1;
}
for(int i = 0; i < distance; i++) {
xPosition += delta;
draw();
}
}
public void slowMoveVertical(int distance) {
int delta;
if(distance < 0) {
delta = -1;
distance = -distance;
}
else {
delta = 1;
}
for(int i = 0; i < distance; i++) {
yPosition += delta;
draw();
}
}
public void changeSize(int newHeight, int newWidth) {
erase();
height = newHeight;
width = newWidth;
draw();
}
public void changeColor(String newColor) {
color = newColor;
draw();
}
private void draw() {
if(isVisible) {
Canvas canvas = Canvas.getCanvas();
int[] xpoints = { xPosition, xPosition + (width/2), xPosition + width };
int[] ypoints = { yPosition + height, yPosition, yPosition + height};
canvas.draw(this, color, new Polygon(xpoints, ypoints, 3));
canvas.wait(10);
}
}
private void erase() {
if(isVisible) {
Canvas canvas = Canvas.getCanvas();
canvas.erase(this);
}
}
}
嗨,歡迎來到堆棧溢出。 請不要要求你的作業的解決方案,嘗試自己找一個好方法,以成爲一個更好的開發者;-) –
刪除多餘的評論 – stealthjong