如何让我的程序意识到JFrame的边界已经改变?
我有一个JFrame,声明为:
JFrame myFrame = new JFrame("My Rad and Sick Pong Game");
myFrame.setSize(1024,768);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
我还有一种只在鼠标悬停在JFrame上时才能玩游戏的方法
boolean mouseOnScreen = false;
Point zero = myFrame.getLocationOnScreen();
int zeroX = (int) zero.getX();
int zeroY = (int) zero.getY();
if (mouseX > zeroX && mouseX < zeroX + getWidth()){
if (mouseY > zeroY && mouseY < zeroY + getHeight()){
mouseOnScreen = true;
}
}
return mouseOnScreen;
当JFrame处于与它开始时相同的位置时,这很有效,从(0,0)延伸到(1024,768)。但是,如果它被移动,JFrame的边界不会改变,所以我的鼠标“离开JFrame”,即使它仍然在里面,因为它还没有意识到JFrame被移动了。
我认为myFrame.getLocationOnScreen
会让它发挥作用,但事实并非如此。
有什么想法吗?感谢。
注意:
编辑:添加了更多代码:
我的主要代码:
running = false;
repaint();
while (mouseOnScreen(mouseY, mouseX, myFrame)) //Update Game
{
//Mouse Code
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
mouseY = (int) b.getY();
mouseX = (int) b.getX();
//Run
repaint();
running = true;
moveBall();
movePaddle(mouseY);
moveEnemyPaddle();
//Code to sleep for 30ms to allow time for execution was here
}
}
private boolean mouseOnScreen(int mouseX, int mouseY, JFrame myFrame) {
boolean mouse = false;
Point zero = myFrame.getLocationOnScreen();
int zeroX = (int) zero.getX();
int zeroY = (int) zero.getY();
if (mouseX > zeroX && mouseX < zeroX + getWidth()) {
if (mouseY > zeroY && mouseY < zeroY + getHeight()) {
mouse = true;
}
}
return mouse;
}
@Override
public void paint(Graphics g) {
super.paint(g);
//(my other drawing stuff was here, removed because irrelevant)
if (!running) {
g.fillRect(0, 0, getWidth(), getHeight());
}
}
我相信这一切都是相关的。感谢你们到目前为止的时间!