import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.ArrayList; public class DetectMouseClickOnImageWithJFrame extends JFrame { // Create an ArrayList of JLabels; each JLabel will contain an ImageIcon of an // "apple", since (unlike an Image) an ImageIcon can be assigned to a JLabel; // each JLabel will also be assigned a MouseListener, since a MouseListener // cannot be assigned directly to an ImageIcon (or an Image) private ArrayList apples = new ArrayList(); // Create ArrayLists containing the coordinates of the "apples" (JLabels) private ArrayList applesX = new ArrayList(); private ArrayList applesY = new ArrayList(); private ImageIcon apple = new ImageIcon("data_files/apple.png"); public static void main(String[] args) { new DetectMouseClickOnImageWithJFrame(); } // Constructor public DetectMouseClickOnImageWithJFrame() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 250); setTitle("Detecting a Mouse Click on an Image on a JFrame"); setLocationRelativeTo(null); setResizable(false); setVisible(true); setFocusable(true); addMouseListener(new InnerMouseListener()); // Add three "apple" images to the ArrayList by creating JLabels, assigning an // "apple" ImageIcon to each JLabel, and adding MouseListeners to the JLabels for (int i = 0; i < 3; i++) { apples.add(new JLabel()); apples.get(i).setIcon(apple); apples.get(i).addMouseListener(new InnerMouseListener()); } repaint(); // Set the 'X' and 'Y' coordinates for the three "apple" images (JLabels) applesX.add(20); applesY.add(72); applesX.add(179); applesY.add(212); applesX.add(335); applesY.add(117); } public void paint(Graphics g) { // Draw the JFrame background g.setColor(Color.BLACK); g.fillRect(0, 0, 400, 250); // Draw the "apple" images at the 'X' and 'Y' coordinates specified above for (int i = 0; i < apples.size(); i++) g.drawImage(apple.getImage(), applesX.get(i), applesY.get(i), this); } // Creating an inner class that extends the 'MouseAdapter' class allows the // 'mouseClicked' method to be used without having to implement the four // remaining (unused) methods of the MouseListener interface public class InnerMouseListener extends MouseAdapter { public void mouseClicked(MouseEvent event) { // Run through the elements of the 'apples' ArrayList to see if one of the // "apple" images (JLabels) has been clicked for (int i = 0; i < apples.size(); i++) { // Create a "rectangle" around each JLabel in the ArrayList Rectangle rApple = new Rectangle(applesX.get(i), applesY.get(i), apple.getImage().getWidth(null), apple.getImage().getHeight(null)); // See if the coordinates where the mouse was clicked are within the // "rectangle" that was created around the "apple" image (JLabel) if (rApple.contains(event.getX(), event.getY())) System.out.println("The mouse was clicked on apple #" + (i + 1) + "."); } } } }