您的小程序通过 getLocationOnScreen() 知道它的位置
这是一个 Java 小程序,当您在其中时,它会打印鼠标光标的屏幕位置:
ScreenTest.java:
import java.awt.Point;
import java.awt.Graphics;
import java.applet.Applet;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
public class ScreenTest extends Applet implements MouseMotionListener
{
public ScreenTest()
{
this.addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent e)
{
}
public void mouseMoved(MouseEvent e)
{
Graphics g = getGraphics();
Point loc=getLocationOnScreen();
String s=(loc.getX()+e.getX())+":"+(loc.getY()+e.getY());
g.clearRect(0,0,1000,100);
g.drawString(s, 10, 10);
}
}
屏幕测试.html:
<html>
<head></head>
<body>
<applet code="ScreenTest.class" name="screenTest" height=100 width=1000></applet>
</body>
</html>
这是一个由 javascript 调用的更简单的示例。小程序在页面的左上角是 1px x 1px。
ScreenTest2.java:
import java.awt.Point;
import java.applet.Applet;
public class ScreenTest2 extends Applet
{
public String test(int x, int y)
{
Point loc=getLocationOnScreen();
return (loc.getX()+x)+":"+(loc.getY()+y);
}
}
屏幕测试2.html:
<html>
<head></head>
<body onclick="buttonClick(event);" style="margin:0; border:0; height:800px">
<applet code="ScreenTest2.class" name="screenTest2" height=1 width=1></applet>
</body>
<script>
function buttonClick(evt)
{
alert(screenTest2.test(evt.clientX,evt.clientY));
}
</script>
</html>