1

I am trying to make my own components such as buttons and other things for my program and I cannot seem to get the MouseEvent to work properly. I want to be able to detect if a mouse pointer is within the bounds of a component and my methods always returns false for some reason.

Here is an example of what I tried:

public void mousePressed(MouseEvent e) {

    for (MyComponent component : components) {

        // getBounds() returns a Rectangle.
        if (component.getBounds().contains(e.getX(), e.getY())) {
            System.out.println("PRESSED");
        }

    }

}

Another example:

public void mouseEntered(MouseEvent e) {

    for (MyComponent component : components) {

        boolean isWithinBounds = isWithinBounds(e.getX(), e.getY(), component);

        if (isWithinBounds) {

            component.mouseEntered(e);

        }

    }

}

private boolean isWithinBounds(int x, int y, MyComponent component) {

    // getBounds() returns a Rectangle.
    if (x >= component.getBounds().x
            && x <= component.getBounds().x + component.getBounds().width
            && y >= component.getBounds().y
            && y <= component.getBounds().y + component.getBounds().height) {

        return true;

    } else {

        return false;

    }

}

Does anyone know why this does not work and how I should do it instead?

Thanks in advance!

1 Answers1

1
You should add a mouse listener and react to the mouseEntered-Event:

JFrame.addMouseListener( new MouseAdapter() {

     public void mouseEntered( MouseEvent e ) {
        // your code here
     }
} );

Maybe helpful: Finding if my mouse is inside a rectangle in Java

Community
  • 1
  • 1