Java Swing mousePressed和getSource()在JPanel上未显示绘制的形状 [英] Java Swing mousePressed and getSource() not showing drawed shapes on JPanel

查看:129
本文介绍了Java Swing mousePressed和getSource()在JPanel上未显示绘制的形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试开发一个谜题.我所得到的只是我在运动场和游戏机件上的应用程序.下一步是单击我的一个游戏作品以选择它,并能够使用箭头键将其移动(此外,如果下一步(将为100像素)不包含该内容,则我希望它们仅移动任何其他游戏作品).

I am currently trying to develop a puzzle. All I got is my application with my playing-field and gaming-pieces. Next step is to click on one of my gaming-piece to select it and be able to move it with the arrow-keys (furthermore I want to them only to move, if the next step - which will be 100 pixels - does not contain any other gaming-piece).

我当前遇到的问题:在主JPanel上使用addMouseListener()然后使用getSource()只返回我的运动场(在我的代码中称为View),但是我需要它来返回所需的游戏件(例如topLeft).我已经尝试过将getSource()强制转换为Piece,但这不起作用(Cannot cast View to Piece).

The problem I'm currently running into: Using addMouseListener() on my main JPanel and then using getSource() only returns my playing-field (called View in my code) but I need it to return the desired gaming-piece (such as topLeft). I already tried casting getSource() to Piece but this does not work (Cannot cast View to Piece).

因此,我需要找到一种添加鼠标侦听器的方法,该侦听器将返回被单击的游戏零件,以便我可以更改位置并检查是否与其他任何游戏零件发生碰撞.预先感谢!

So, I need to find a way to add a mouse listener which returns the gaming-piece that was clicked on so that I can change the location and check for any collision with any other gaming-piece. Thanks in advance!

通过@camickr编辑代码.

Edited code thanks to @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");
        }
    }
    }
}

推荐答案

因此,我需要找到一种添加鼠标侦听器的方法,该方法可以返回被单击的游戏件

So, I need to find a way to add a mouse listener which returns the gaming-piece that was clicked

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

You use the getX() and getY() methods from the MouseEvent.

然后,您遍历片段" ArrayList,并在每个Piece中包含的Shape上调用contains(...方法,以查看鼠标指针是否包含在片段中.

Then you iterate through your "pieces" ArrayList and invoke the contains(... method on the Shape contained in each Piece to see if the mouse point is contained in the piece.

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

So you will also need to add a getShape(...) method to your "Piece" class so you can access the Shape of each Piece.

所以您的基本逻辑可能类似于:

So your basic logic might be something like:

//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(..)方法中的绘画代码就是:

Then the painting code in the draw(..) method is just:

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

不需要转换或翻译.

因此使用形状:

//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对象.请考虑所建议的概念,并且不要认为已发布的代码是完美的,因为它显然尚未经过测试.

This currently matches your Piece class which expects a Shape object anyway. Please think about the concept being suggested and don't assume posted code is perfect since it obviously hasn't been tested.

这篇关于Java Swing mousePressed和getSource()在JPanel上未显示绘制的形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆