how to detect if someone clicks on a jpanel in java

Solutions on MaxInterview for how to detect if someone clicks on a jpanel in java by the best coders in the world

showing results for - "how to detect if someone clicks on a jpanel in java"
Melyne
04 Nov 2020
1import javax.swing.*;
2import java.awt.*;
3import java.awt.event.*;
4
5public class TestFrame extends JFrame{
6
7    public TestFrame(int size){
8        JPanel content = new JPanel(new GridLayout(size, size));
9        JPanel[] panel = new JPanel[size * size];
10        PanelListener listener = new PanelListener();
11
12        for(int i = 0; i < panel.length; i++){
13            panel[i] = new JPanel();
14            panel[i].setBackground(Color.white);
15            panel[i].addMouseListener(listener);
16            content.add(panel[i]);
17        }
18
19        this.add(content);
20    }
21
22    // MouseListener offers the method mouseClicked(MouseEvent e)
23    private class PanelListener implements MouseListener {
24
25        @Override
26        public void mouseClicked(MouseEvent event) {
27                    /* source is the object that got clicked
28                     * 
29                     * If the source is actually a JPanel, 
30                     * then will the object be parsed to JPanel 
31                     * since we need the setBackground() method
32                     */
33            Object source = event.getSource();
34            if(source instanceof JPanel){
35                JPanel panelPressed = (JPanel) source;
36                panelPressed.setBackground(Color.blue);
37            }
38        }
39
40        @Override
41        public void mouseEntered(MouseEvent arg0) {}
42
43        @Override
44        public void mouseExited(MouseEvent arg0) {}
45
46        @Override
47        public void mousePressed(MouseEvent arg0) {}
48
49        @Override
50        public void mouseReleased(MouseEvent arg0) {}
51
52    }
53
54    public static void main(String[] args){
55        TestFrame theGUI = new TestFrame(8);
56        theGUI.setTitle("Grid");
57        theGUI.setVisible(true);
58        theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
59        theGUI.setSize(400,400);
60
61    }
62}