0

Does anybody of You know a method to detect, which card on the board was clicked? I got a class drawing multiple card objects on a JPanel. Now I've implemented a MouseAdapter. On a mouse click it should check whether a card was clicked or not. Additionally it should tell me which object was clicked.

Any theoretical ideas, procedures or methods how to achieve this?

Card card = new Card();
public void paint(Graphics g) { 
    g.drawImage(card.getImage(), card.getX(), card.getY(), null); 
}
user2410644
  • 3,861
  • 6
  • 39
  • 59
  • For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve). – Andrew Thompson Jan 09 '14 at 18:19
  • ..but definitely look into using a sub-class of [`Rectangle2D`](http://docs.oracle.com/javase/7/docs/api/java/awt/geom/Rectangle2D.html). Since the parent class `implements Shape`, it can then be used just like seen in the example linked below. – Andrew Thompson Jan 09 '14 at 18:22

1 Answers1

2

How do you draw the cards? If using the Java-2D API and Shape instances, it can be quite easy. See this answer for an example of collision detection using complex shapes, then look closely at the JavaDocs for Shape for other methods that might help for determining if a Point is inside a shape.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • I created a class called "Card". This card contains a BufferedImage. The main core class with the JPanel contains the paint(Graphics g) method and looks as following: public void paint(Graphics g) { g.drawImage(card.getImage(), card.getX(), card.getY(), null); } Thats a simplified example how the drawing works – user2410644 Jan 08 '14 at 13:59
  • Oops sorry forgot about all that. Edited my post! – user2410644 Jan 08 '14 at 14:28