Java Swing mousePressed 和 getSource() 在 JPanel 上未显示绘制的形状



我目前正在尝试开发一个谜题。我得到的只是我的应用程序与我的运动场和游戏棋子。下一步是单击我的一个游戏棋子以选择它并能够使用箭头键移动它(此外,如果下一步(将是 100 像素)不包含任何其他游戏棋子,我只想移动它们)。

我目前遇到的问题:在我的主JPanel上使用addMouseListener()然后使用getSource()只返回我的游戏场地(在我的代码中称为View),但我需要它来返回所需的游戏部分(例如topLeft)。我已经尝试将getSource()铸造到Piece但这不起作用(Cannot cast View to Piece)。

因此,我需要找到一种方法来添加一个鼠标侦听器,该侦听器返回单击的游戏棋子,以便我可以更改位置并检查与任何其他游戏棋子的任何冲突。提前感谢!

多亏了@camickr编辑了代码。

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Puzzle {
public static void main(String[] args) {
SwingUtilities.invokeLater(Puzzle::new);
}
private final static int[] SHAPE_X = { -100, 100, 100, 0, 0, -100 };
private final static int[] SHAPE_Y = { -100, -100, 0, 0, 100, 100 };
public Puzzle() {
JFrame frame = new JFrame("Puzzle");
frame.setSize(400, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
View view = new View();
frame.setContentPane(view);
view.addMouseListener(new MouseAdapterMod(view));
Shape polyShape = new Polygon(SHAPE_X, SHAPE_Y, SHAPE_X.length);
Piece topLeft = new Piece(Color.YELLOW, polyShape,   0, 100, 100);
view.pieces.add(topLeft);
Piece topRight = new Piece(Color.CYAN, polyShape, 90, 300, 100);
view.pieces.add(topRight);
Piece bottomRight = new Piece(Color.GREEN,  polyShape, 180, 300, 300);
view.pieces.add(bottomRight);
Piece bottomLeft = new Piece(Color.RED,  polyShape, 270, 100, 300);
view.pieces.add(bottomLeft);
Piece square = new Piece(Color.ORANGE, new Rectangle(200, 200), 0, 100, 100);
view.pieces.add(square);
frame.setVisible(true);
}
}
class View extends JPanel {
final List<Piece> pieces = new ArrayList<>();
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D gc = (Graphics2D) g;
for (Piece piece : pieces) {
piece.draw(gc);
}
}
}
class Piece {
final Color color;
final Shape shape;
final int angle;
int x;
int y;
Piece(Color color, Shape shape, int angle, int x, int y) {
this.color = color;
this.shape = shape;
this.angle = angle;
this.x = x;
this.y = y;
}
void draw(Graphics2D gc) {
AffineTransform tf = gc.getTransform();
gc.translate(x, y);
gc.rotate(Math.toRadians(angle));
gc.setColor(color);
gc.fill(shape);
gc.setTransform(tf);
}
Shape getShape() {
return shape;
}
}
class MouseAdapterMod extends MouseAdapter {
final View view;
public MouseAdapterMod(View view) {
this.view = view;
}
@Override
public void mousePressed(MouseEvent e) {
for(Piece piece : view.pieces) {
if(piece.getShape().contains(e.getX(), e.getY())) {
System.out.println("yes");
}
}
}
}

因此,我需要找到一种方法来添加鼠标侦听器,该侦听器返回单击的游戏棋子

您可以使用 MouseEvent 中的 getX() 和 getY() 方法。

然后,循环访问"片段"ArrayList,并在每个Piece中包含的Shape上调用contains(...方法,以查看鼠标点是否包含在片段中。

因此,您还需要向"Piece"类添加一个getShape(...)方法,以便可以访问每个PieceShape

编辑:

因此,您的基本逻辑可能是这样的:

//Shape polyShape = new Polygon(SHAPE_X, SHAPE_Y, SHAPE_X.length);
//Piece topLeft = new Piece(Color.YELLOW, polyShape,   0, 100, 100);
Polygon topLeftPolygon = new Polygon(SHAPE_X, SHAPE_Y, SHAPE_X.length);
topLeftPolygon.translate(100, 100);
//topLeftPolygon = ShapeUtils.rotate(...); // do rotation when required
Piece topLeft = new Piece(Color.YELLOW, topLeftPolygon);

那么 draw(..) 方法中的绘画代码就是:

gc.setColor(color);
gc.fill(shape);

无需转换或翻译。

编辑 2:

所以使用形状:

//topLeftPolygon = ShapeUtils.rotate(...); // do rotation when required
//Piece topLeft = new Piece(Color.YELLOW, topLeftPolygon);
Shape topLeftShape = ShapeUtils.rotate(...); // do rotation when required
Piece topLeft = new Piece(Color.YELLOW, topLeftShape);

这当前与您的 Piece 类匹配,该类无论如何都需要一个 Shape 对象。请考虑所建议的概念,不要假设发布的代码是完美的,因为它显然没有经过测试。

我看到你已经用我从这个问题中的答案作为你的益智游戏的基础,而不是继续你自己的代码。 理解,我给了你一个最小的、完整的、可验证的例子,用于在JPanel上绘制形状。 我从来没有说过它适合直接使用;如果事实上,通过使示例"最小",可能会导致扩展代码以支持命中测试之类的事情变得更加困难。 但是既然你选择继续我的代码作为基础......

命中测试问题来自以下事实:鼠标单击位于视图的坐标系中,但形状正在平移并旋转到其他各种位置进行绘制。 可以通过反转变换、将鼠标位置转换为形状的坐标系,然后使用Shape.contains(Point2D)来解决此问题。

class Piece {
// ... omitted for brevity ...
public boolean hitTest(Point point) {
AffineTransform tf = new AffineTransform();
tf.translate(x, y);
tf.rotate(Math.toRadians(angle));
try {
Point2D pnt = tf.inverseTransform(point, null);
return shape.contains(pnt);
} catch (NoninvertibleTransformException e) {
return false;
}
}
}

然后,只需遍历每个部分,并询问它是否在鼠标的位置下。

class View extends JPanel {
// ... omitted for brevity ...
Piece hitTest(MouseEvent e) {
Point pnt = e.getPoint();
for (Piece piece : pieces) {
if (piece.hitTest(pnt))
return piece;
}
return null;
}
}

请注意,我在这里返回的是Piece,而不是Shape。 由于 5 件中有 4 件使用相同的polyShape形状,因此这不是很有用。

可以使用 Java8 流缩短hitTest()

Piece hitTest(MouseEvent e) {
final Point pnt = e.getPoint();
return pieces.stream()
.filter(piece -> piece.hitTest(pnt))
.findFirst()
.orElse(null);
}

如果碎片可以重叠,则看起来在顶部的那个是最后一个绘制的。findFirst()将返回在给定鼠标点绘制的最底部的片段,而不是最顶部的片段。 以下更改将纠正该行为:

Piece hitTest(MouseEvent e) {
final Point pnt = e.getPoint();
return pieces.stream()
.filter(piece -> piece.hitTest(pnt))
.reduce((first, second) -> second)
.orElse(null);
}

最新更新