【发布时间】:2016-02-23 20:00:36
【问题描述】:
我正在尝试获取鼠标相对于窗口的坐标。 我知道我需要参考 JFrame 或其他东西,但我一生都无法弄清楚如何,我的班级为我提供了这个初学者代码,并且我从那里构建了它。
public class TheGame extends JFrame
{
public static final int WIDTH = 785;
public static final int HEIGHT = 670;
public static int width;
public static int height;
public static int borderX;
public static int borderY;
public TheGame()
{
super("PLATFORMGAME");
setSize(WIDTH,HEIGHT);
PlatformGame game = new PlatformGame();
((Component)game).setFocusable(true);
getContentPane().add(game);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main( String args[] )
{
TheGame run = new TheGame();
}
}
这是我的鼠标监听类:
public class mouse extends JFrame {
static Point p;
BufferedImage sprite;
public mouse() {
Point p = MouseInfo.getPointerInfo().getLocation();
try {
sprite = ImageIO.read(new File("mouse_pointer.png")) ;
} catch (IOException e1) {
e1.printStackTrace();
}
}
public Point getlocation() {
return p = MouseInfo.getPointerInfo().getLocation();
}
public static double getNorP(double uno, double dos) {
if ((uno - dos) > 0) {return -1;}
else {return 1;}
}
public static double getX(Char c) {
return MouseInfo.getPointerInfo().getLocation().x ;
//return MouseInfo.getPointerInfo().getLocation().x - ReferenceJFrame.getLocationOnScreen().x;
}
public static double getY(Char c) {
return MouseInfo.getPointerInfo().getLocation().y -29;
//return MouseInfo.getPointerInfo().getLocation().y - ReferenceJFrame.getLocationOnScreen().y;
}
public static double getXD(Char c) {
return Math.abs(c.rX-(double)getX(c));
}
public static double getYD(Char c) {
return Math.abs(c.rY-(double)getY(c));
}
// public static float getAngle(Point target,int x,int y) {
// return (float) Math.toDegrees(Math.atan2(getX()-x, getY()-y));
}
public static double getXP(Char c) {
return (getXD(c))/(getXD(c)+getYD(c)) * getNorP(c.rX,getX(c));
}
public static double getYP(Char c) {
return (getYD(c))/(getXD(c)+getYD(c)) * getNorP(c.rY,getY(c));
}
public void draw(Graphics window, Char c) {
window.drawImage(sprite,(int) getX(c)-16,(int) getY(c)-8, 16, 16, null);
}
}
这会返回鼠标相对于屏幕而不是窗口的坐标。除了 JFrame 类型的东西,我了解相当多的 java。
【问题讨论】:
-
首先查看How to Write a Mouse Listener。将
MouseListener添加到PlatformGame,这将触发组件坐标空间内的鼠标事件
标签: java jframe mouse mouselistener