java - 如何使用 MouseListener 移动不同的形状
问题描述
我有一个程序可以绘制我放入 ArrayList 的不同形状,它可以很好地迭代形状来绘制它们,但是我移动它们的方法不起作用。我的 move() 方法有问题吗?
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyShapes extends JPanel {
private Point2D.Float position;
private final DifferentShapes[] shapes = new DifferentShapes[]{new Circle(), new Triangle(), new Square()};
MovingAdapter ma = new MovingAdapter();
public MyShapes() {
addMouseMotionListener(ma);
addMouseListener(ma);
}
interface DifferentShapes {
void paint(Graphics2D graphics);
boolean contains(int x, int y);
void move(int dx, int dy);
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D graphics = (Graphics2D) g;
for (DifferentShapes shape : this.shapes) {
shape.paint(graphics);
}
}
移动适配器类
public class MovingAdapter extends MouseAdapter {
private int x;
private int y;
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
public void mouseDragged(MouseEvent e) {
final int dx = e.getX() - x;
final int dy = e.getY() - y;
for (DifferentShapes shape : shapes) {
if (shape.contains(x, y)) {
shape.move(dx, dy);
}
}
x += dx;
y += dy;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Shapes World");
MyShapes m = new MyShapes();
m.setDoubleBuffered(true);
frame.add(m);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
类圆
class Circle implements MyShapes.DifferentShapes {
public Circle() {
}
public static Ellipse2D.Float myCr = new Ellipse2D.Float(10,10, 100, 100);
public void paint(Graphics2D graphics) {
Graphics2D circle = (Graphics2D) graphics;
circle.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
circle.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
circle.setColor(new Color(0, 0, 117));
circle.fill(myCr);
}
@Override
public boolean contains(int x, int y) {
if (myCr.contains(x, y)) {
}
return true;
}
public void move(int dx, int dy) {
myCr.x += dx;
myCr.y += dy;
}
}
当我使用常规 if 语句时,它可以正常工作,但不能在 for 循环和我的 move() 方法中
解决方案
逻辑是正确的,您正在正确更改坐标。您只需要调用repaint()
以显示更改。
if (shape.contains(x, y)) {
shape.move(dx, dy);
repaint();
}
推荐阅读
- javascript - javascript数组过滤器在反应中非常慢
- acumos - 载入 Python 模型时出现 Acumos 载入错误
- python - Python SDK 未经授权访问 Key Vault
- angular - 数据绑定失败,因为变量不更新其值
- javascript - 如何防止 OpenLayers 应用像素提示?
- sql - 如何使用 PL SQL 将数据插入到 oracle 数据库表中,其中包括一年中的 365 天
- java - 使用供应商重构方法传递函数作为参数
- regex - Vue 属性 v-validate 中的正则表达式
- selenium - Webdriver 无法连接到 Selenium 服务器
- android - 在 MainActivity 中打开 Switch 时,如何为其他 Activity 添加计时器?