我正在做一個家庭作業的ms繪畫風格程序。在這個家庭作業中,你應該能夠右擊一個形狀並在屏幕上移動它。填充的形狀可以在形狀內部的任何地方右鍵單擊,其中未填充的形狀應該右鍵單擊並在形狀的邊界上進行選擇。拖放填充的形狀與未填充的形狀[作業]
我遇到的問題是,當我最初啓動程序時,繪製和未填充的形狀,並試圖拖動它,它會拖動,但一旦我再次放下它,它的行爲是正確的,併成爲不可複製的,所有未來未填充的形狀相應地起作用
TLDR:我希望所有填充的形狀都是可拖動的,並且所有未填充的形狀都是不可裁剪的。如果它是第一個放置的形狀,未填充的形狀(出於某種原因)可拖動。拖曳未填充的形狀後,它的行爲正確。
下面是相關的代碼:
private boolean isFilled = false;
private JCheckBox fill = new JCheckBox("Filled");
private int indexToMove;
塗料成份
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.clearRect(0, 0, getWidth(), getHeight());
for (int i = 0; i < shapes.size(); i++) {
shapes.get(i).draw(g);
}
repaint();
}
的actionPerformed我補釦
else if (e.getSource() == fill) {
if (fill.isSelected()) {
isFilled = true;
} else {
isFilled = false;
}
}
這是我開始拖放
部分鼠標的時候按住
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
for (int i = 0; i < shapes.size(); i++) {
if (shapes.get(i).isSelected(e.getX(), e.getY())) {
System.out.println("Shape contained in: " + i);
indexToMove = i;
}
}
}
}
鼠標拖動
public void mouseDragged(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
if (indexToMove >= 0) {
shapes.get(indexToMove).move(e.getX(), e.getY());
}
}
}
MOUSE RELEASED
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
indexToMove = -1;
}
}
這些是相關SHAPE類代碼
public class MyRectangle extends Rectangle implements MyShape {
private Color color;
private boolean filled = false;
private int x, y, dx, dy, height, width;
public MyRectangle(Color color, boolean filled, int x, int y, int endX, int endY) {
this.color = color;
this.filled = filled;
this.x = x;
this.y = y;
this.dx = endX;
this.dy = endY;
}
@Override
public void draw(Graphics g) {
...
if (!filled) {
g.drawRect(x, y, width, height);
}
if (filled) {
g.fillRect(x, y, width, height);
}
}
這是我檢查它是否填充/ UNF ILLED 製出的只發生後,我拖放填充的形狀ONE TIME
@Override
public boolean isSelected(int clickX, int clickY) {
boolean selected = false;
if(filled == false){
System.out.println("unfilled shape, do not move");
selected = false;
}
else if (filled == true) {
if ((clickX > x) && (clickX < dx) && (clickY > y) && (clickY < dy)) {
selected = true;
} else {
selected = false;
}
}
return selected;
}
public void move(int offsetX, int offsetY) {
int centerX = (dx + x)/2;
int centerY = (dy + y)/2;
System.out.println("CenterX: " + centerX + " CenterY: " + centerY);
if (offsetX > centerX) {
offsetX = offsetX - centerX;
x += offsetX;
dx += offsetX;
} else if (offsetX < centerX) {
offsetX = centerX - offsetX;
x -= offsetX;
dx -= offsetX;
}
if (offsetY > centerY) {
offsetY = offsetY - centerY;
y += offsetY;
dy += offsetY;
}
else if (offsetY < centerY) {
offsetY = centerY - offsetY;
y -= offsetY;
dy -= offsetY;
}
}
知道這是相當多的代碼,我試圖砍掉任何似乎並不相關。讓我知道你是否需要看更多!