【发布时间】:2019-03-05 13:08:30
【问题描述】:
我目前正在尝试开发一个谜题。我得到的只是我的运动场和游戏部件的应用程序。下一步是单击我的一个游戏块以选择它并能够使用箭头键移动它(此外,我希望它们只移动,如果下一步 - 将是 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()来查找选择了哪个Piece。 -
@Arnaud 使用
getComponentAt()或View的任何类似方法?我也试过了,一般也只返回View。
标签: java swing jpanel shapes mouselistener