Jan Tennert
Jan Tennert

Reputation: 79

Java MouseAdapter

So I have my custom mouse adapter. I want to call a method if: The x and y coordinates are in a Rectangle with for example the coordinates x = 40 y = 40 and the width = 10 length = 10. How can I check if the x and y coordinates (of the mouse) are in the rectangle? I tried this:

@Override
public void mouseClicked(MouseEvent e) {
    if(isXinBounds(e.getX()) || isYinBounds(e.getY())) {
        //This happens if the mouse click is in the rectangle
    }
}

//Check if the x coordinate of the mouse click is in the rectangle
private boolean isXinBounds(int x) {
    if(x <= ob.getBounds().getX() + ob.getBounds().getWidth() / 2 && x >= ob.getBounds().getX() - ob.getBounds().getWidth() / 2) return true;
    return false;
}

//Check if the y coordinate of the mouse click is in the rectangle
private boolean isYinBounds(int y) {
    if(y <= ob.getBounds().getY() + ob.getBounds().getHeight() / 2 && y >= ob.getBounds().getY() - ob.getBounds().getHeight() / 2) return true;
    return false;
}

But that didn't work

Upvotes: 0

Views: 385

Answers (2)

camickr
camickr

Reputation: 324108

The x and y coordinates are in a Rectangle

The Rectangle class already supports a contains(…) method.

You can just use:

if (yourRectangle.contains(e.getPoint())
    // do something

Upvotes: 1

Frakcool
Frakcool

Reputation: 11143

You're making a really weird formula to check if your click is in bounds of your rectangle.

If we set the rectangle coords:

x = 10
y = 10
width = 50
height = 50

And create a new Rectangle with those values:

Rectangle rect = new Rectangle(x, y, widht, height)

We can then do this for both X & Y

private boolean xIsInBounds(int x) {
    if (x >= rect.x && x <= rect.width + x) {
        return true;
    }
    return false;
}

Because we check for the X & Y values as they are going to be always the same, but we have to add the X & Y values to the width and height respectively due to it being moved due to the X & Y values not being on 0,0.

The other issue in your code is that you're asking:

if (xIsInBounds(...) || yIsInBounds(...)) { ... }

When it should be an && instead of ||.

Here's the code that produces the following output in the form of a Minimal Reproducible Example

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ClickOnBounds extends MouseAdapter {
    private JFrame frame;
    private JPanel pane;
    private static final int X_COORD = 10;
    private static final int Y_COORD = 10;
    private static final int RECT_WIDTH = 50;
    private static final int RECT_HEIGHT = 50;
    private Rectangle rect = new Rectangle(X_COORD, Y_COORD, RECT_WIDTH, RECT_HEIGHT);

    @SuppressWarnings("serial")
    private void createAndShowGUI() {
        frame = new JFrame(this.getClass().getSimpleName());
        pane = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.draw(rect);
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(70, 70);
            }
        };

        pane.addMouseListener(this);
        frame.add(pane);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        super.mouseClicked(e);
        if (xIsInBound(e.getX()) && yIsInBound(e.getY())) {
            System.out.println("Yes! " + e.getX() + " " + e.getY());
        } else {
            System.out.println("No! " + e.getX() + " " + e.getY());
        }
    }

    private boolean xIsInBound(int x) {
        if (x >= rect.x && x <= rect.width + X_COORD) {
            return true;
        }
        return false;
    }

    private boolean yIsInBound(int y) {
        if (y >= rect.y && y <= rect.height + Y_COORD) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ClickOnBounds()::createAndShowGUI);
    }
}

enter image description here

And, as you can see in the image above, it works perfectly.

Upvotes: 1

Related Questions