AleMal
AleMal

Reputation: 2077

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.setContentPane(content);
    wind.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    wind.setLocation(100, 100);
    wind.setSize(new Dimension(500,500));
    wind.setVisible(true);

  }

  Exercise2() {
    setBackground(Color.BLACK);
    square = new drawRec();
  }

  public void paintComponent(Graphics g) {

    super.paintComponent(g); 
    square.draw(g, 100, 90);
  }

  private class drawRec extends JPanel implements MouseListener {


    drawRec() {
        addMouseListener(this);
    }

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

        g.setColor(Color.BLUE);
        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) {
        System.out.println("Test");
    }

    public void mouseReleased(MouseEvent e) {}

   }
}

Thanks in advance

Upvotes: 0

Views: 266

Answers (1)

khelwood
khelwood

Reputation: 59096

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() {
    setBackground(Color.BLACK);
    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.

Upvotes: 3

Related Questions