下面列出了怎么用java.awt.MouseInfo的API类实例代码及写法,或者点击链接到github查看源代码。
@SneakyThrows
private CompletableFuture<Optional<RequestTypePlugin>> getRequestTypePluginQuick(Node node) {
List<RequestTypePlugin> requestTypePlugins = plugins.loadRequestTypePlugins();
if (requestTypePlugins.size() == 0)
throw new IllegalArgumentException("No RequestType plugins found");
ContextMenu ctxMenu = new ContextMenu();
CompletableFuture<RequestTypePlugin> f = new CompletableFuture<RequestTypePlugin>();
requestTypePlugins.forEach(rtp -> {
var itm = new MenuItem(rtp.getRequestType());
itm.setOnAction(e -> {
f.complete(rtp);
});
ctxMenu.getItems().add(itm);
});
ctxMenu.setOnCloseRequest(e -> f.complete(null));
Point location = MouseInfo.getPointerInfo().getLocation();
ctxMenu.show(node, location.getX(), location.getY());
return f.thenApply(Optional::ofNullable);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
String deckName = (String) value;
JLabel lbl = new JLabel(deckName);
lbl.setOpaque(true);
if (isSelected) {
lbl.setForeground(table.getSelectionForeground());
lbl.setBackground(table.getSelectionBackground());
} else {
lbl.setForeground(table.getForeground());
lbl.setBackground(table.getBackground());
}
Point mp = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(mp, table);
int mRow = table.rowAtPoint(mp);
int mCol = table.columnAtPoint(mp);
if (row == mRow && column == mCol) {
lbl.setForeground(Color.blue);
lbl.setFont(withUnderline);
}
return lbl;
}
/**
* 处理鼠标移动
*/
public void mouseMove(String info) {
String args[] = info.split(",");
String x = args[0];
String y = args[1];
float px = Float.valueOf(x);
float py = Float.valueOf(y);
PointerInfo pinfo = MouseInfo.getPointerInfo(); // 得到鼠标的坐标
java.awt.Point p = pinfo.getLocation();
double mx = p.getX(); // 得到当前电脑鼠标的坐标
double my = p.getY();
try {
java.awt.Robot robot = new Robot();
robot.mouseMove((int) (mx + px), (int) (my + py));
} catch (AWTException e) {
}
}
/**
* Scrolls the {@link ScrollPane} along the given {@code edge}.
*
* @param edge The scrolling side.
*/
private void scroll ( Edge edge ) {
if ( edge == null ) {
return;
}
Point screenLocation = MouseInfo.getPointerInfo().getLocation();
Point2D localLocation = scrollPane.screenToLocal(screenLocation.getX(), screenLocation.getY());
switch ( edge ) {
case LEFT:
scrollPane.setHvalue(scrollPane.getHvalue() + Math.min(1.0, localLocation.getX() / 2.0) / scrollPane.getWidth());
break;
case RIGHT:
scrollPane.setHvalue(scrollPane.getHvalue() + Math.max(1.0, ( localLocation.getX() - scrollPane.getWidth() ) / 2.0) / scrollPane.getWidth());
break;
case TOP:
scrollPane.setVvalue(scrollPane.getVvalue() + Math.min(1.0, localLocation.getY() / 2.0) / scrollPane.getHeight());
break;
case BOTTOM:
scrollPane.setVvalue(scrollPane.getVvalue() + Math.max(1.0, ( localLocation.getY() - scrollPane.getHeight() ) / 2.0) / scrollPane.getHeight());
break;
}
}
/** Handle that this tab was dragged elsewhere, or drag aborted */
private void handleDragDone(final DragEvent event)
{
final DockItem item = dragged_item.getAndSet(null);
if (item != null && !event.isDropCompleted())
{
// Would like to position new stage where the mouse was released,
// but event.getX(), getSceneX(), getScreenX() are all 0.0.
// --> Using MouseInfo, which is actually AWT code
final Stage other = item.detach();
final PointerInfo pi = MouseInfo.getPointerInfo();
if (pi != null)
{
final Point loc = pi.getLocation();
other.setX(loc.getX());
other.setY(loc.getY());
}
}
event.consume();
}
public void handlePressedMouseButtons(WorldView view) {
double deltaX = MouseInfo.getPointerInfo().getLocation().x - lastPosition.x;
double deltaY = MouseInfo.getPointerInfo().getLocation().y - lastPosition.y;
if (rightButtonPressed || leftButtonPressed) {
if (Math.abs(deltaX) > 0) {
controller.changeOffsetX(((int) deltaX) * view.getZoomFactor());
}
if (Math.abs(deltaY) > 0) {
controller.changeOffsetY(((int) deltaY) * view.getZoomFactor());
}
}
lastPosition = MouseInfo.getPointerInfo().getLocation();
}
@Override
public void paint(Graphics g, JComponent c) {
LAFUtilities.setProperties(g, c);
if (c.isOpaque()) {
ImageLibrary.drawTiledImage("image.background.FreeColButton",
g, c, null);
}
super.paint(g, c);
AbstractButton a = (AbstractButton) c;
if (a.isRolloverEnabled()) {
Point p = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(p, c);
boolean rollover = c.contains(p);
if (rollover) {
paintButtonPressed(g, (AbstractButton) c);
}
}
}
public void post() {
// update mouse w/system location
mousePoint = MouseInfo.getPointerInfo().getLocation();
DebugView.setValue("mousePoint.x", mousePoint.x);
DebugView.setValue("mousePoint.y", mousePoint.y);
// wrap mouse
int padding = 1;
if(p.frameCount > lastLoopFrame + 1) {
if(mousePoint.x == p.displayWidth - 1 && lastMousePoint.x < mousePoint.x) { Mouse.movePointerTo(padding, mousePoint.y); lastLoopFrame = p.frameCount; }
else if(mousePoint.x == 0 && lastMousePoint.x > mousePoint.x) { Mouse.movePointerTo(p.displayWidth - padding, mousePoint.y); lastLoopFrame = p.frameCount; }
else if(mousePoint.y == p.displayHeight - 1 && lastMousePoint.y < mousePoint.y) { Mouse.movePointerTo(mousePoint.x, padding); lastLoopFrame = p.frameCount; }
else if(mousePoint.y == 0 && lastMousePoint.y > mousePoint.y) { Mouse.movePointerTo(mousePoint.x, p.displayHeight - padding); lastLoopFrame = p.frameCount; }
}
// store last mouse position
lastMousePoint.setLocation(mousePoint);
}
public void disableScanning() {
if (withSwaying) {
stopSwayingTimer();
}
stopScanning();
stopScanTimer();
Toolkit.getDefaultToolkit().removeAWTEventListener(autoScanMouseListener);
Toolkit.getDefaultToolkit().removeAWTEventListener(mouseDirectedScanListener);
Toolkit.getDefaultToolkit().removeAWTEventListener(directedScanKeyboardListener);
if (autoAutoScan) {
Point p = MouseInfo.getPointerInfo().getLocation();
cursorPosX = p.x;
cursorPosY = p.y;
tickCountTime = System.currentTimeMillis();
}
}
/**
* Returns the current pointer location.
*
* @return The current pointer location.
*/
public static Point getPointerLocation() {
// XXX: Ensure AWT is not considered to be in headless mode, as
// otherwise MouseInfo#getPointerInfo() will not work; therefore
// adjust AWT headless property, if required
String awtHeadlessPropertyValue = System
.getProperty(JAVA_AWT_HEADLESS_PROPERTY);
if (awtHeadlessPropertyValue != null
&& awtHeadlessPropertyValue != Boolean.FALSE.toString()) {
System.setProperty(JAVA_AWT_HEADLESS_PROPERTY,
Boolean.FALSE.toString());
}
// retrieve mouse location
PointerInfo pi = MouseInfo.getPointerInfo();
java.awt.Point mp = pi.getLocation();
// restore AWT headless property
if (awtHeadlessPropertyValue != null) {
System.setProperty(JAVA_AWT_HEADLESS_PROPERTY,
awtHeadlessPropertyValue);
}
return new Point(mp.x, mp.y);
}
@java.lang.SuppressWarnings("squid:S2189")
private void mainLoop() throws InterruptedException {
long start = System.currentTimeMillis();
int captureCount = 0;
Point previous = new Point(-1, -1);
//noinspection InfiniteLoopStatement
while (true) {
final Point current = MouseInfo.getPointerInfo().getLocation();
++captureCount;
if (!current.equals(previous) && fireOnLocationUpdated(current)) {
previous = current;
}
final int delayedCaptureCount = syncOnTick(start, captureCount);
captureCount += delayedCaptureCount;
}
}
public Joystick(int port, Computer computer) {
super(computer);
centerPoint = new Point(screenSize.width / 2, screenSize.height / 2);
this.port = port;
if (port == 0) {
xSwitch = (MemorySoftSwitch) SoftSwitches.PDL0.getSwitch();
ySwitch = (MemorySoftSwitch) SoftSwitches.PDL1.getSwitch();
} else {
xSwitch = (MemorySoftSwitch) SoftSwitches.PDL2.getSwitch();
ySwitch = (MemorySoftSwitch) SoftSwitches.PDL3.getSwitch();
}
lastMouseLocation = MouseInfo.getPointerInfo().getLocation();
try {
robot = new Robot();
} catch (AWTException ex) {
Logger.getLogger(Joystick.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Create a mouse movement event as if the mouse just
* moved to its current position.
* @param c the base swing component to relativize the mouse location
* @return the mouse event
*/
public static UIMouse createCurrent(Component c) {
UIMouse m = new UIMouse();
m.type = UIMouse.Type.MOVE;
PointerInfo pointerInfo = MouseInfo.getPointerInfo();
if (pointerInfo != null) {
Point pm = pointerInfo.getLocation();
Point pc = new Point(0, 0);
try {
pc = c.getLocationOnScreen();
} catch (IllegalStateException ex) {
// ignored
}
m.x = pm.x - pc.x;
m.y = pm.y - pc.y;
}
return m;
}
/**
* Creates update progress bar.
*
* @param max max file size
* @param urlBase base url for the browser
* @param fromVersion the version the update is based on, may be <code>null</code>
* @param toVersion the version the download leads to
*/
UpdateProgressBar(final int max, final String urlBase, final String fromVersion, final String toVersion) {
super("Downloading...", MouseInfo.getPointerInfo().getDevice().getDefaultConfiguration());
setLocationByPlatform(true);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new UpdateProgressBarWindowListener());
this.max = max;
this.urlBase = urlBase;
this.fromVersion = fromVersion;
this.toVersion = toVersion;
try {
final URL url = this.getClass().getClassLoader().getResource(
ClientGameConfiguration.get("GAME_ICON"));
setIconImage(new ImageIcon(url).getImage());
} catch (final RuntimeException e) {
// in case that resource is not available
}
initializeComponents();
this.pack();
}
/**
* Workaround for JDK bug 6663119, it ensures that first item in submenu is
* correctly selected during keyboard navigation.
*/
private void ensureSelected() {
if (menu.getMenuComponentCount() <= 0) {
return;
}
Component first = menu.getMenuComponent(0);
if (!(first instanceof JMenuItem)) {
return;
}
Point loc = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(loc, menu);
MenuElement[] selPath
= MenuSelectionManager.defaultManager().getSelectedPath();
// apply workaround only when mouse is not hovering over menu
// (which signalizes mouse driven menu traversing) and only
// when selected menu path contains expected value - submenu itself
if (!menu.contains(loc) && selPath.length > 0
&& menu.getPopupMenu() == selPath[selPath.length - 1]) {
// select first item in submenu through MenuSelectionManager
MenuElement[] newPath = new MenuElement[selPath.length + 1];
System.arraycopy(selPath, 0, newPath, 0, selPath.length);
JMenuItem firstItem = (JMenuItem) first;
newPath[selPath.length] = firstItem;
MenuSelectionManager.defaultManager().setSelectedPath(newPath);
}
}
public void setEnabled( boolean enabled ) {
if( this.enabled == enabled )
return;
this.enabled = enabled;
rootPane.getGlassPane().setVisible( enabled );
Toolkit toolkit = Toolkit.getDefaultToolkit();
if( enabled )
toolkit.addAWTEventListener( keyListener, AWTEvent.KEY_EVENT_MASK );
else
toolkit.removeAWTEventListener( keyListener );
if( enabled ) {
Point pt = new Point( MouseInfo.getPointerInfo().getLocation() );
SwingUtilities.convertPointFromScreen( pt, rootPane );
lastX = pt.x;
lastY = pt.y;
inspect( lastX, lastY );
} else {
lastComponent = null;
inspectParentLevel = 0;
if( highlightFigure != null )
highlightFigure.getParent().remove( highlightFigure );
highlightFigure = null;
if( tip != null )
tip.getParent().remove( tip );
tip = null;
}
propertyChangeSupport.firePropertyChange( "enabled", !enabled, enabled );
}
private void updateClientCursor() {
Point p = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(p, this);
Component target = SwingUtilities.getDeepestComponentAt(this, p.x, p.y);
if (target != null) {
content.setCursor(target.getCursor());
}
}
private void updateClientCursor() {
Point p = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(p, this);
Component target = SwingUtilities.getDeepestComponentAt(this, p.x, p.y);
if (target != null) {
content.setCursor(target.getCursor());
}
}
private void updateClientCursor() {
Point p = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(p, this);
Component target = SwingUtilities.getDeepestComponentAt(this, p.x, p.y);
if (target != null) {
content.setCursor(target.getCursor());
}
}
public static Point getMouseLocation() {
try {
// can test with GraphicsEnvironment.isHeadless()
return MouseInfo.getPointerInfo().getLocation();
} catch (Exception myException) {
myException.printStackTrace();
}
return new Point();
}
public Location getLocation() {
PointerInfo mp = MouseInfo.getPointerInfo();
if (mp != null) {
return new Location(MouseInfo.getPointerInfo().getLocation());
} else {
Debug.error("Mouse: not possible to get mouse position (PointerInfo == null)");
return null;
}
}
private Point getCurrentCursorLocation() {
Point res = null;
PointerInfo pi = MouseInfo.getPointerInfo();
if( null != pi ) {
res = pi.getLocation();
}
return res;
}
private Rectangle getScreenBounds() {
Rectangle res = null;
PointerInfo pi = MouseInfo.getPointerInfo();
if( null != pi ) {
GraphicsDevice gd = pi.getDevice();
if( gd != null ) {
GraphicsConfiguration gc = gd.getDefaultConfiguration();
if( gc != null ) {
res = gc.getBounds();
}
}
}
return res;
}
/** Workaround for JDK bug 6663119, it ensures that first item in submenu
* is correctly selected during keyboard navigation.
*/
private void ensureSelected () {
if (menu.getMenuComponentCount() <=0) {
return;
}
Component first = menu.getMenuComponent(0);
if (!(first instanceof JMenuItem)) {
return;
}
PointerInfo pointerInfo = MouseInfo.getPointerInfo();
if (pointerInfo == null) {
return; // probably a mouseless computer
}
Point loc = pointerInfo.getLocation();
SwingUtilities.convertPointFromScreen(loc, menu);
MenuElement[] selPath =
MenuSelectionManager.defaultManager().getSelectedPath();
// apply workaround only when mouse is not hovering over menu
// (which signalizes mouse driven menu traversing) and only
// when selected menu path contains expected value - submenu itself
if (!menu.contains(loc) && selPath.length > 0 &&
menu.getPopupMenu() == selPath[selPath.length - 1]) {
// select first item in submenu through MenuSelectionManager
MenuElement[] newPath = new MenuElement[selPath.length + 1];
System.arraycopy(selPath, 0, newPath, 0, selPath.length);
JMenuItem firstItem = (JMenuItem)first;
newPath[selPath.length] = firstItem;
MenuSelectionManager.defaultManager().setSelectedPath(newPath);
}
}
private void updateClientCursor() {
Point p = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(p, this);
Component target = SwingUtilities.getDeepestComponentAt(this, p.x, p.y);
if (target != null) {
content.setCursor(target.getCursor());
}
}
@Override
public void mouseMove(int x, int y, int mouseMoveTimeMs) {
try {
Robot robot = new Robot();
if (mouseMoveTimeMs <= 0) {
robot.mouseMove(x, y);
return;
}
Point startLoc = MouseInfo.getPointerInfo().getLocation();
double startX = startLoc.x;
double distanceX = Math.abs(startX - x);
double currentX = startLoc.x;
double currentY = startLoc.y;
long startMillis = System.currentTimeMillis();
int currentMillis = 0;
double durationMillis = 1000;
int sign = startX < x ? 1 : -1;
// m = (y2 - y1) / (x2 - x1)
double slope = ((double) y - startLoc.y) / (x - startLoc.x);
while (currentMillis < durationMillis) {
currentMillis = (int) (System.currentTimeMillis() - startMillis);
currentX = startX + easeOutCubic(currentMillis / durationMillis) * distanceX * sign;
// m = (y2 - ym) / (x2 - xm)
// ym = y2 - m (x2 - xm)
currentY = y - (slope * (x - currentX));
robot.mouseMove((int) currentX, (int) currentY);
// robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
// robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
robot.mouseMove(x, y);
} catch (AWTException ex) {
Logger.getLogger(Automator.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void display() {
// Execute on EDT to avoid deadlock (see 6280857).
SunToolkit.executeOnEventHandlerThread(target, new Runnable() {
public void run() {
if (liveArguments.isDisposed()) {
return;
}
String tooltipString = liveArguments.getTooltipString();
if (tooltipString == null) {
return;
} else if (tooltipString.length() > TOOLTIP_MAX_LENGTH) {
textLabel.setText(tooltipString.substring(0, TOOLTIP_MAX_LENGTH));
} else {
textLabel.setText(tooltipString);
}
Point pointer = AccessController.doPrivileged(
new PrivilegedAction<Point>() {
public Point run() {
if (!isPointerOverTrayIcon(liveArguments.getBounds())) {
return null;
}
return MouseInfo.getPointerInfo().getLocation();
}
});
if (pointer == null) {
return;
}
show(new Point(pointer.x, pointer.y), TOOLTIP_MOUSE_CURSOR_INDENT);
}
});
}
@Override
protected void paintComponent(Graphics g) {
final Point windowLocation = getRootPane().getParent().getLocationOnScreen();
final Dimension size = getRootPane().getSize();
final Rectangle rectangle = new Rectangle(windowLocation.x, windowLocation.y, size.width, size.height);
fBackground.paintBackground(g, rectangle.contains(MouseInfo.getPointerInfo().getLocation()), fCornerRadius);
}
private void updateRollOver() {
boolean wasBorderShown = mShowBorder;
Point location = MouseInfo.getPointerInfo().getLocation();
UIUtilities.convertPointFromScreen(location, this);
mShowBorder = isOver(location.x, location.y);
if (wasBorderShown != mShowBorder) {
repaint();
}
}
private void updateRollOver() {
boolean wasBorderShown = mShowBorder;
Point location = MouseInfo.getPointerInfo().getLocation();
UIUtilities.convertPointFromScreen(location, this);
mShowBorder = isOver(location.x, location.y);
if (wasBorderShown != mShowBorder) {
repaint();
}
}