almal almal - 8 months ago 58
Java Question

Java nested class dont react to MouseListener events

in Java i'm try to create a class for display into a JFrame two JPanel components and add a Mouselistener at one of that.
I create a main JPanel and nested into it a private class named drawRec (JPanel type) used for draw a rectangle who should handle the mouse events over him but when I make a click, nothing happens. here is my code:

public class Exercise2 extends JPanel {

private drawRec square;

public static void main(String[] args) {
JFrame wind = new JFrame();
Exercise2 content = new Exercise2();
wind.setLocation(100, 100);
wind.setSize(new Dimension(500,500));


Exercise2() {
square = new drawRec();

public void paintComponent(Graphics g) {

square.draw(g, 100, 90);

private class drawRec extends JPanel implements MouseListener {

drawRec() {

private void draw(Graphics g, int x, int y) {

g.fillRect(x, y, 50, 20);


public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

public void mousePressed(MouseEvent e) {

public void mouseReleased(MouseEvent e) {}


Thanks in advance


Your frame doesn't contain a drawRec panel. It contains an Exercise2 panel that calls drawRec.draw() to paint its content. If you click, you are clicking in an Exercise2 panel, which does not have a mouse listener.

Perhaps you should merge these two classes. At least you must add the mouse listener to a component that is actually added to the frame.

The shortest fix might be:

Exercise2() {
    square = new drawRec();
    this.addMouseListener(square); // add this line

In that case you are still not using drawRec as a panel (because you are not adding it to anything), but you can use it as a mouse listener for your Exercise2 panel.