我正在尝试为我的程序制作自己的组件,例如按钮和其他东西,但我似乎无法让 MouseEvent 正常工作。我希望能够检测鼠标指针是否在组件的范围内,并且我的方法由于某种原因总是返回 false。
这是我尝试过的示例:
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");
}
}
}
另一个例子:
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;
}
}
有谁知道为什么这不起作用以及我应该如何做?
提前致谢!
最佳答案
You should add a mouse listener and react to the mouseEntered-Event:
JFrame.addMouseListener( new MouseAdapter() {
public void mouseEntered( MouseEvent e ) {
// your code here
}
} );
关于java - 如何检测鼠标指针是否在对象的边界内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35683403/