how to detect if someone clicks on a jpanel in java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TestFrame extends JFrame{

    public TestFrame(int size){
        JPanel content = new JPanel(new GridLayout(size, size));
        JPanel[] panel = new JPanel[size * size];
        PanelListener listener = new PanelListener();

        for(int i = 0; i < panel.length; i++){
            panel[i] = new JPanel();
            panel[i].setBackground(Color.white);
            panel[i].addMouseListener(listener);
            content.add(panel[i]);
        }

        this.add(content);
    }

    // MouseListener offers the method mouseClicked(MouseEvent e)
    private class PanelListener implements MouseListener {

        @Override
        public void mouseClicked(MouseEvent event) {
                    /* source is the object that got clicked
                     * 
                     * If the source is actually a JPanel, 
                     * then will the object be parsed to JPanel 
                     * since we need the setBackground() method
                     */
            Object source = event.getSource();
            if(source instanceof JPanel){
                JPanel panelPressed = (JPanel) source;
                panelPressed.setBackground(Color.blue);
            }
        }

        @Override
        public void mouseEntered(MouseEvent arg0) {}

        @Override
        public void mouseExited(MouseEvent arg0) {}

        @Override
        public void mousePressed(MouseEvent arg0) {}

        @Override
        public void mouseReleased(MouseEvent arg0) {}

    }

    public static void main(String[] args){
        TestFrame theGUI = new TestFrame(8);
        theGUI.setTitle("Grid");
        theGUI.setVisible(true);
        theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        theGUI.setSize(400,400);

    }
}

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source