public void setLocation(Component source, Point location) { int fontSize = source.getFont().getSize(); location.translate(1, fontSize + 3); Point screenPos = source.getLocationOnScreen(); location.translate(screenPos.x, screenPos.y); getView().setLocation(location); }
/** * Displays the popup menu at the position x,y in the coordinate space of the component invoker. * * @param invoker the component in whose space the popup menu is to appear * @param x the x coordinate in invoker's coordinate space at which the popup menu is to be * displayed * @param y the y coordinate in invoker's coordinate space at which the popup menu is to be * displayed */ public void show(Component invoker, int x, int y) { if (DEBUG) { System.out.println("in JPopupMenu.show "); } setInvoker(invoker); Frame newFrame = getFrame(invoker); if (newFrame != frame) { // Use the invoker's frame so that events // are propagated properly if (newFrame != null) { this.frame = newFrame; if (popup != null) { setVisible(false); } } } Point invokerOrigin; if (invoker != null) { invokerOrigin = invoker.getLocationOnScreen(); // To avoid integer overflow long lx, ly; lx = ((long) invokerOrigin.x) + ((long) x); ly = ((long) invokerOrigin.y) + ((long) y); if (lx > Integer.MAX_VALUE) lx = Integer.MAX_VALUE; if (lx < Integer.MIN_VALUE) lx = Integer.MIN_VALUE; if (ly > Integer.MAX_VALUE) ly = Integer.MAX_VALUE; if (ly < Integer.MIN_VALUE) ly = Integer.MIN_VALUE; setLocation((int) lx, (int) ly); } else { setLocation(x, y); } setVisible(true); }
public static void captureScreen(Component Area) { // Find out where the user would like to save their screen shot String fileName = null; JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Screen Shots", "png"); chooser.setFileFilter(filter); int returnVal = chooser.showSaveDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File saveFile = new File(chooser.getSelectedFile().getPath() + ".png"); fileName = saveFile.toString(); // Check to see if we will overwrite the file if (saveFile.exists()) { int overwrite = JOptionPane.showConfirmDialog(null, "File already exists, do you want to overwrite?"); if (overwrite == JOptionPane.CANCEL_OPTION || overwrite == JOptionPane.CLOSED_OPTION || overwrite == JOptionPane.NO_OPTION) { return; } } } // If they didn't hit approve, return else { return; } // Determine the exact coordinates of the screen that is to be captured Dimension screenSize = Area.getSize(); Rectangle screenRectangle = new Rectangle(); screenRectangle.height = screenSize.height; screenRectangle.width = screenSize.width; screenRectangle.x = Area.getLocationOnScreen().x; screenRectangle.y = Area.getLocationOnScreen().y; // Here we have to make the GUI Thread sleep for 1/4 of a second // just to give the save dialog enough time to close off of the // screen. On slower computers they were capturing the screen // before the dialog was out of the way. try { Thread.currentThread(); Thread.sleep(250); } catch (InterruptedException e1) { e1.printStackTrace(); } // Attempt to capture the screen at the defined location. try { Robot robot = new Robot(); BufferedImage image = robot.createScreenCapture(screenRectangle); ImageIO.write(image, "png", new File(fileName)); } catch (AWTException e) { e.printStackTrace(); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Could not save screen shoot at: " + fileName); e.printStackTrace(); } }
/** * Create a new mouse event. * * @param eventType * @param button * @param lParam * @return mouse event */ private MouseEvent createMouseEvent(int eventType, int button, MSLLHOOKSTRUCT lParam) { POINT pt = lParam.pt; // FIXME race condition where relativeTo might not be visible Point rl = relativeTo.getLocationOnScreen(); int x = pt.x - rl.x; int y = pt.y - rl.y; return new MouseEvent( relativeTo, eventType, lParam.time.longValue(), 0, x, y, 0, false, button); }
public static void setPositionRelativeToParent( Window w, Component parent, int hOffset, int vOffset) { try { Point p = parent.getLocationOnScreen(); int x = (int) p.getX() + hOffset; int y = (int) p.getY() + vOffset; w.setLocation(x, y); w.pack(); } catch (Throwable t) { } }
@Override public Dimension getPreferredSize() { final Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); Point p = null; if (focusOwner != null && focusOwner.isShowing()) { p = focusOwner.getLocationOnScreen(); } return computeNotBiggerDimension(super.getPreferredSize().getSize(), p); }
@Override public void mousePressed(MouseEvent e) { selectedComponent = (Component) e.getSource(); // Point tempPoint = selectedComponent.getLocation(); offset = e.getPoint(); dragging = true; // System.out.println(selectedComponent.getParent()); try { if (selectedComponent.getParent().equals(workPanel)) { view.workPanel.remove(selectedComponent); view.workPanel.revalidate(); view.layer.add(selectedComponent, new Integer(1)); view.layer.revalidate(); layer.repaint(); // offset = selectedComponent.getLocationOnScreen(); // selectedComponent.setBounds(MouseInfo.getPointerInfo().getLocation().x, // MouseInfo.getPointerInfo().getLocation().y, cardHomes[1].getSize().width, // cardHomes[1].getSize().height); // selectedComponent.setLocation(MouseInfo.getPointerInfo().getLocation()); /*System.out.println(MouseInfo.getPointerInfo().getLocation()); System.out.println(selectedComponent.getLocation()); System.out.println(selectedComponent.getLocationOnScreen()); System.out.println(tempPoint);*/ selectedComponent.setLocation(-200, -200); // selectedComponent.setSize(cardHomes[1].getSize().width, cardHomes[1].getSize().height); } else if (selectedComponent.getParent().equals(holdPanel)) { int tempX = selectedComponent.getX(); int tempY = selectedComponent.getLocationOnScreen().y; view.holdPanel.remove(selectedComponent); view.holdPanel.revalidate(); view.layer.add(selectedComponent, new Integer(1)); view.layer.revalidate(); layer.repaint(); selectedComponent.setLocation(tempX, tempY); } /* else { System.out.println("normal workpanel:"+workPanel); System.out.println("parent:"+selectedComponent.getParent()); }*/ } catch (Exception ex) { System.out.println("error removing from panel"); ex.printStackTrace(); } }
public static Point getRelLocation(Component c) { if (c == null || !c.isShowing()) { return new Point(0, 0); } Container parent = getRootContainer(c); if ((parent != null) && parent.isShowing()) { Point p1 = c.getLocationOnScreen(); Point p2 = parent.getLocationOnScreen(); return new Point(p1.x - p2.x, p1.y - p2.y); } return new Point(0, 0); }
/** * Create a new mouse wheel event. * * <p>In Windows the rotation amount is positive when moving the wheel away from the user whereas * in Java the rotation amount is negative when moving the wheel away from the user. * * <p>This implementation adjusts the sign so that the value is correct for Java. * * @param eventType * @param lParam * @return mouse wheel event */ private MouseWheelEvent createMouseWheelEvent(int eventType, MSLLHOOKSTRUCT lParam) { POINT pt = lParam.pt; // FIXME race condition where relativeTo might not be visible Point rl = relativeTo.getLocationOnScreen(); int x = pt.x - rl.x; int y = pt.y - rl.y; int wheelRotation = lParam.mouseData.intValue() >> 16; return new MouseWheelEvent( relativeTo, eventType, lParam.time.longValue(), 0, x, y, 0, false, MouseWheelEvent.WHEEL_UNIT_SCROLL, 1, wheelRotation * -1); }
/** * Constructs a <code>MouseEvent</code> object with the specified source component, type, time, * modifiers, coordinates, click count, popupTrigger flag, and button number. * * <p>Creating an invalid event (such as by using more than one of the old _MASKs, or * modifier/button values which don't match) results in unspecified behavior. An invocation of the * form <tt>MouseEvent(source, id, when, modifiers, x, y, clickCount, popupTrigger, button)</tt> * behaves in exactly the same way as the invocation <tt> {@link #MouseEvent(Component, int, long, * int, int, int, int, int, int, boolean, int) MouseEvent}(source, id, when, modifiers, x, y, * xAbs, yAbs, clickCount, popupTrigger, button)</tt> where xAbs and yAbs defines as source's * location on screen plus relative coordinates x and y. xAbs and yAbs are set to zero if the * source is not showing. This method throws an <code>IllegalArgumentException</code> if <code> * source</code> is <code>null</code>. * * @param source The <code>Component</code> that originated the event * @param id An integer indicating the type of event. For information on allowable values, see the * class description for {@link MouseEvent} * @param when A long integer that gives the time the event occurred. Passing negative or zero * value is not recommended * @param modifiers a modifier mask describing the modifier keys and mouse buttons (for example, * shift, ctrl, alt, and meta) that are down during the event. Only extended modifiers are * allowed to be used as a value for this parameter (see the {@link InputEvent#getModifiersEx} * class for the description of extended modifiers). Passing negative parameter is not * recommended. Zero value means that no modifiers were passed * @param x The horizontal x coordinate for the mouse location. It is allowed to pass negative * values * @param y The vertical y coordinate for the mouse location. It is allowed to pass negative * values * @param clickCount The number of mouse clicks associated with event. Passing negative value is * not recommended * @param popupTrigger A boolean that equals {@code true} if this event is a trigger for a popup * menu * @param button An integer that indicates, which of the mouse buttons has changed its state. The * following rules are applied to this parameter: * <ul> * <li>If support for the extended mouse buttons is {@link * Toolkit#areExtraMouseButtonsEnabled() disabled} by Java then it is allowed to create * {@code MouseEvent} objects only with the standard buttons: {@code NOBUTTON}, {@code * BUTTON1}, {@code BUTTON2}, and {@code BUTTON3}. * <li>If support for the extended mouse buttons is {@link * Toolkit#areExtraMouseButtonsEnabled() enabled} by Java then it is allowed to create * {@code MouseEvent} objects with the standard buttons. In case the support for * extended mouse buttons is {@link Toolkit#areExtraMouseButtonsEnabled() enabled} by * Java, then in addition to the standard buttons, {@code MouseEvent} objects can be * created using buttons from the range starting from 4 to {@link * java.awt.MouseInfo#getNumberOfButtons() MouseInfo.getNumberOfButtons()} if the mouse * has more than three buttons. * </ul> * * @throws IllegalArgumentException if {@code button} is less then zero * @throws IllegalArgumentException if <code>source</code> is null * @throws IllegalArgumentException if {@code button} is greater then BUTTON3 and the support for * extended mouse buttons is {@link Toolkit#areExtraMouseButtonsEnabled() disabled} by Java * @throws IllegalArgumentException if {@code button} is greater then the {@link * java.awt.MouseInfo#getNumberOfButtons() current number of buttons} and the support for * extended mouse buttons is {@link Toolkit#areExtraMouseButtonsEnabled() enabled} by Java * @throws IllegalArgumentException if an invalid <code>button</code> value is passed in * @throws IllegalArgumentException if <code>source</code> is null * @see #getSource() * @see #getID() * @see #getWhen() * @see #getModifiers() * @see #getX() * @see #getY() * @see #getClickCount() * @see #isPopupTrigger() * @see #getButton() * @since 1.4 */ public MouseEvent( Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger, int button) { this(source, id, when, modifiers, x, y, 0, 0, clickCount, popupTrigger, button); Point eventLocationOnScreen = new Point(0, 0); try { eventLocationOnScreen = source.getLocationOnScreen(); this.xAbs = eventLocationOnScreen.x + x; this.yAbs = eventLocationOnScreen.y + y; } catch (IllegalComponentStateException e) { this.xAbs = 0; this.yAbs = 0; } }
/** * Creates a video stream of the interactions with the given component at the specified frame rate * and saves it as the given file. */ public static Processor recordVideo(Component component, int fps, File dest) { if (component == null) return null; Dimension size = component.getSize(); Point location = component.getLocationOnScreen(); String loc = MessageFormat.format( "screen://{0},{1},{2},{3}/{4}", new Object[] { new Integer(location.x), new Integer(location.y), new Integer(size.width - size.width % 8), new Integer(size.height - size.height % 8), new Integer(fps) }); MediaLocator mSource = new MediaLocator(loc); Processor p = null; try { DataSource data = Manager.createDataSource(mSource); p = Manager.createProcessor(mSource); waitForState(p, Processor.Configured); p.setContentDescriptor(new FileTypeDescriptor("video.x_msvideo")); p.getTrackControls()[0].setFormat(new VideoFormat(VideoFormat.MJPG)); waitForState(p, Processor.Realized); DataSource data2 = p.getDataOutput(); String path = dest.getParent(); String name = dest.getName(); if (!name.toLowerCase().endsWith(".avi")) name += ".avi"; MediaLocator mediaDest = new MediaLocator(new File(path, name).toURL()); DataSink dataSink = Manager.createDataSink(data2, mediaDest); dataSink.open(); dataSink.start(); p.start(); } catch (Exception ex) { ex.printStackTrace(); p = null; } return p; }
protected void customizePopup(BasicComboPopup popup) { scrollPane = getScrollPane(popup); if (popupWider) popupWider(popup); checkHorizontalScrollBar(popup); // For some reason in JDK7 the popup will not display at its preferred // width unless its location has been changed from its default // (ie. for normal "pop down" shift the popup and reset) Component comboBox = popup.getInvoker(); Point location = comboBox.getLocationOnScreen(); if (popupAbove) { int height = popup.getPreferredSize().height; popup.setLocation(location.x, location.y - height); } else { int height = comboBox.getPreferredSize().height; popup.setLocation(location.x, location.y + height - 1); popup.setLocation(location.x, location.y + height); } }
synchronized void popup(int x, int y, Component component, String text) { invalidate(); textLabel.setText(text); textLabel.setForeground(ToolTipManager.getInstance().foreground); textLabel.setBackground(ToolTipManager.getInstance().background); validate(); pack(); try { if (x != -1 && y != -1) { setLocation(x + 8, y + 8); } else { Point p = component.getLocationOnScreen(); Dimension s = component.getSize(); setLocation(p.x + 8, p.y + s.height + 8); } setVisible(true); toFront(); lastShow = System.currentTimeMillis(); dismissed = false; } catch (IllegalComponentStateException icse) { } }
private void pointOnComp(final Component comp, final Robot robot) { Rectangle bounds = new Rectangle(comp.getLocationOnScreen(), comp.getSize()); robot.mouseMove(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2); }
/** * Converts relative coordinates inside one of the components laying on the designer to * coordinates relative to handleLayer() * * @see #handleLayer() * @see #componentLayer() * @see #findComponent(org.netbeans.jemmy.ComponentChooser, int) * @see #findComponent(org.netbeans.jemmy.ComponentChooser) * @see #findComponent(java.lang.Class, int) * @see #findComponent(java.lang.Class) * @param subComponent Component in designer. * @param localCoords Local <code>subComponent</code>'s coordinates * @return coordinates relative to handle layer */ public Point convertCoords(Component subComponent, Point localCoords) { Point subLocation = subComponent.getLocationOnScreen(); Point location = handleLayer().getLocationOnScreen(); return (new Point( subLocation.x - location.x + localCoords.x, subLocation.y - location.y + localCoords.y)); }
@Override public LRESULT callback(int nCode, WPARAM wParam, MSLLHOOKSTRUCT lParam) { Logger.trace("callback(nCode={},wParam={},lParam={})", nCode, wParam, lParam); if (nCode >= 0) { Window window = SwingUtilities.getWindowAncestor(relativeTo); Logger.trace("window={}", window); // Is the window active... if (window != null && window.isActive()) { Logger.trace("window is active"); // Is the component showing... // TODO is this still needed or is isActive good enough? if (relativeTo.isShowing() && relativeTo.isValid()) { Logger.trace("window is visible"); // Did the event occur inside the component bounds... int absX = lParam.pt.x; int absY = lParam.pt.y; // FIXME there is a race here where relativeTo may no longer be visible, should // I lock the component tree - is that OK from non-EDT? Point componentPoint = relativeTo.getLocationOnScreen(); int relX = componentPoint.x; int relY = componentPoint.y; int relW = relX + relativeTo.getWidth(); int relH = relY + relativeTo.getHeight(); if (absX >= relX && absY >= relY && absX < relW && absY < relH) { Logger.trace("event inside component bounds"); if (!this.mouseEntered) { this.mouseEntered = true; fireMouseEvent(MouseEvent.MOUSE_ENTERED, MouseEvent.NOBUTTON, lParam); } // The event did occur inside the component bounds, so translate it... switch (wParam.intValue()) { case WM_MOUSEMOVE: fireMouseMotionEvent(MouseEvent.MOUSE_MOVED, MouseEvent.NOBUTTON, lParam); break; case WM_LBUTTONDOWN: fireMouseEvent(MouseEvent.MOUSE_PRESSED, MouseEvent.BUTTON1, lParam); break; case WM_LBUTTONUP: fireMouseEvent(MouseEvent.MOUSE_RELEASED, MouseEvent.BUTTON1, lParam); break; case WM_RBUTTONDOWN: fireMouseEvent(MouseEvent.MOUSE_PRESSED, MouseEvent.BUTTON2, lParam); break; case WM_RBUTTONUP: fireMouseEvent(MouseEvent.MOUSE_RELEASED, MouseEvent.BUTTON2, lParam); break; case WM_MBUTTONDOWN: fireMouseEvent(MouseEvent.MOUSE_PRESSED, MouseEvent.BUTTON3, lParam); break; case WM_MBUTTONUP: fireMouseEvent(MouseEvent.MOUSE_RELEASED, MouseEvent.BUTTON3, lParam); break; case WM_MOUSEWHEEL: fireMouseWheelEvent(MouseEvent.MOUSE_WHEEL, lParam); break; default: break; } } else { Logger.trace("event outside component bounds"); if (this.mouseEntered) { this.mouseEntered = false; fireMouseEvent(MouseEvent.MOUSE_EXITED, MouseEvent.NOBUTTON, lParam); } } } } } return USER32_INSTANCE.CallNextHookEx(hHook, nCode, wParam, lParam.getPointer()); }
private static final void moveToCenterOfComponent(Robot r, Component c) { Point p = c.getLocationOnScreen(); p.translate(c.getWidth() / 2, c.getHeight() / 2); r.mouseMove((int) p.getX(), (int) p.getY()); }
void doTest() throws Exception { ArrayList<Component> components = new ArrayList(); components.add(button); components.add(buttonLW); components.add(textField); components.add(textArea); components.add(list); components.add(listLW); int keys[]; String OS = System.getProperty("os.name").toLowerCase(); System.out.println(OS); if (OS.contains("os x") || OS.contains("sunos")) { keys = new int[] {KeyEvent.VK_SHIFT, KeyEvent.VK_CONTROL, KeyEvent.VK_ALT, KeyEvent.VK_META}; } else { keys = new int[] {KeyEvent.VK_SHIFT, KeyEvent.VK_CONTROL, KeyEvent.VK_ALT}; } for (Component c : components) { System.out.print(c.getClass().getName() + ": "); Point origin = c.getLocationOnScreen(); int xc = origin.x + c.getWidth() / 2; int yc = origin.y + c.getHeight() / 2; Point center = new Point(xc, yc); robot.delay(robotDelay); robot.glide(origin, center); robot.click(); robot.delay(robotDelay); for (int k = 0; k < keys.length; ++k) { keyPressReceived = false; keyCode = keys[k]; robot.type(keyCode); robot.delay(robotDelay); if (!keyPressReceived) { synchronized (lock) { try { lock.wait(waitDelay); } catch (InterruptedException e) { } } } assertTrue(keyPressReceived, "key press event was not received"); } System.out.println("passed"); } robot.waitForIdle(); frame.dispose(); }
/** * Wrapper for {@code Component.getLocationOnScreen}. * * <p><b>Note:</b> This method is accessed in the current executing thread. Such thread may or may * not be the event dispatch thread (EDT.) Client code must call this method from the EDT. * * @param c the given AWT or Swing {@code Component}. * @return the a point specifying the {@code Component}'s top-left corner in the screen's * coordinate space. */ @RunsInCurrentThread public static @Nonnull Point locationOnScreenOf(@Nonnull Component c) { return new Point(c.getLocationOnScreen()); }