Drag events in Robot class

I am using the Robot class in jdk1.3.1 to record and playback user input. I am getting the list of events and then traversing on it to do the appropriate action, mouse move, key events are played back fine, but I am unable to do mouse drag event.
Here is simplified version of the code:
for(int i = 0; i < aListEvents.size(); i++)
AWTEvent event = (AWTEvent)aListEvents.get(i);
Component c = (Component)event.getSource();
int id = event.getID();
switch(id)
case MouseEvent.MOUSE_MOVED:
int x = ((MouseEvent)e).getX();
int y = ((MouseEvent)e).getY();
m_robot.mouseMove(x,y);
break;
case KeyEvent.KEY_PRESSED:
m_robot.keyPress(((KeyEvent)e).getKeyCode());
break;
case MouseEvent.MOUSE_DRAGGED:
     // do component drag
break;
Is there a way to mimic the drag event during playback and drag the object that was dragged during record?
Any suggestions would be greatly appreciated!!
Thanks :)

This is an old posting, so the answer is probably too late for mamta and has also been answered elsewhere. But for whoever comes across this one, share my piece of experience:
There's no one-to-one mapping between Java events and the system events (which is what Robot is refering to).
After all, a MOUSE_DRAGGED is nothing but a MOUSE_MOVE after a MOUSE_PRESSED. So you can send a MOUSE_DRAGGED along to the robot as a mouseMove, because the Robot/system keeps in mind that the mouse button has been pressed before and therefor the event will appear in the Java event queue as a MOUSE_DRAGGED.
Similar is MOUSE_CLICKED which needn't be replayed at all, because sending a MOUSE_PRESSED and a MOUSE_RELEASED to the Robot will automatically produce a MOUSE_CLICKED in the Java event queue as well.
Same with the key strokes.

Similar Messages

  • Differences between Robot class generated events and real input events

    Hello everyone!
    I'm having a problem with the translation of the description of the awt.Robot class.
    - "This class is used to generate native system input events" -
    Does this mean there is no difference between real input events and generated events from the Robot class? Difference in reference to that the generated events can't be recognized as generated events by the os or programs.
    Thanks in advance.
    Chris B.

    The Robot class will use an interface provided by the operating system to inject events. Those are very close to 'real' input events, but not quite there. There are, for instance, several games out there which have a protection mechanism against Robot's events to prevent scripting/botting. However, any application that is not paying special attention to the event's source will assume that the input events generated by Robot are actually coming from the user, so you can 'control' any application with the exception of the beforementioned games.

  • Drag event handling in JFXPanel has performance implications with expensive event handlers

    We have a drag event handler that is a little expensive, takes something like 20ms. The respective code must be run in a synchronous manner however.
    That is no problem in a pure JavaFX environment, as less drag events are created when CPU load is high.
    However, when embedded into Swing using JFXPanel this adaptation doesn't kick in, lots of drag events are created and the application becomes sluggish.
    Is there a way to mimic what JavaFX does in the JFXPanel scenario?
    The code below is a self-contained example that demonstrates what I'm describing.
    Some results I had:
    -eventHandlerSleep=5 -noswing --> 128 drag events
    -eventHandlerSleep=30 -noswing --> 46 drag events
    -eventHandlerSleep=5  --> 136 drag events
    -eventHandlerSleep=30  --> 135 drag events
    {code}import java.util.Arrays;
    import javax.swing.*;
    import com.sun.glass.ui.Robot;
    import javafx.application.Application;
    import javafx.application.Platform;
    import javafx.embed.swing.JFXPanel;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.BorderPane;
    import javafx.stage.Stage;
    public class DragHandlingTester {
        private static long EVENT_HANDLER_SLEEP = 30;
        public static void main(String[] args) {
            for (String arg : args) {
                if (arg.startsWith("-eventHandlerSleep=")) {
                    EVENT_HANDLER_SLEEP = Long.parseLong(arg.split("=")[1]);
            if (Arrays.asList(args).contains("-noswing")) {
                Application.launch(JavaFXDragHandlingTestApp.class, args);
            } else {
                new SwingDragHandlingTestApp();
        static class SwingDragHandlingTestApp {
            SwingDragHandlingTestApp() {
                JFrame frame = new JFrame();
                final JFXPanel fxMainPanel = new JFXPanel();
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        DragTestScene dragTestScene = new DragTestScene();
                        fxMainPanel.setScene(dragTestScene.createScene());
                frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                frame.getContentPane().add(fxMainPanel);
                frame.setSize(800, 600);
                frame.setVisible(true);
        public static class JavaFXDragHandlingTestApp extends Application {
            @Override
            public void start(Stage primaryStage) {
                primaryStage.setWidth(800);
                primaryStage.setHeight(600);
                primaryStage.setX(0.0);
                primaryStage.setY(0.0);
                DragTestScene dragTestScene = new DragTestScene();
                primaryStage.setScene(dragTestScene.createScene());
                primaryStage.show();
        static class DragTestScene {
            private int drags = 0;
            public Scene createScene() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            // after 1 second drag mouse across window
                            Thread.sleep(1000);
                            Robot robot = com.sun.glass.ui.Application.GetApplication().createRobot();
                            robot.mouseMove(50, 50);
                            robot.mousePress(1);
                            for (int i = 20; i &lt; 700; i = i + 5) {
                                robot.mouseMove(i, 50);
                                Thread.sleep(10);
                            robot.mouseRelease(1);
                        } catch (Exception e) {
                            e.printStackTrace();
                }).start();
                BorderPane borderPane = new BorderPane();
                borderPane.setOnMouseDragged(new EventHandler() {
                    @Override
                    public void handle(MouseEvent mouseEvent) {
                        drags++;
                        try {
                            Thread.sleep(EVENT_HANDLER_SLEEP);
                        } catch (InterruptedException ignored) {
                        System.out.println("Number of drag events: " + drags);
                return new Scene(borderPane);
    {code}

    Ok, I expected something like this to be the reason. We'll probably have to live with it.
    My workaround right now is to use background tasks with an executor that has a single element queue handling the events in order, but rejecting any additional events as long as there is a queued event.
    Still not the same performance as in JavaFX, but at least it's usable now.

  • Simulating mouse drag events?

    Hi all,
    I am wrinting unit tests for my swing application. For one test I want to simulate a drag event over a panel. I have tried JFCUnit, but does not seem to work for this, so I am trying to write my own.
    I create 3 mouse events and post them on the system event queue. A mouse press event, a mouse drag event and a mouse release event. MouseEvent's do let you specify a drag start and a drag end point in their constructor. So I have tried using both, but neither works.
    Am I doing anything wrong? The component I'm operating on gets the mouse pressed and mouse released events, but thats all.
    any help much appreciated,
    Justin

    I tried using the Robot class alright, but it does really wierd things. I sometimes doesn't work for simulating dragging events. I have a component that you can drag anywhere on the screen using the mouse, without having to use the titlebar. I am trying to test this dragging, but with the robot class, it looks like it goes into an infinate recursion. The mouseDragged method gets executed thosands of times, and you can see the panel shifting from its origional position to the new position and back again for a few seconds. Could be a bug in Robot class.

  • Taking screenshot with java applet using java robot class not working

    Hi Everyone,
    I am using the java applet to take screenshot of the web browser using the java's robot class.
    Robot objRobot = new Robot ();
    BufferedImage objBufferedImage = objRobot.createScreenCapture(objRectArea);
    The thing work good in windows system taking screenshot but in case of mac osx i get the blank image.When i check the event viewer in mac osx i get the following error.
    invalid context
    invalid pixel format
    CoreAnimation: rendering error 506
    The problem is coming for all the browser safari,firefox and chrome.My applet is signed applet.
    What might be the reason.An early reply is very valuable.
    My machine configuration is as follows.
    OS : MAC OSX
    Version : 10.6.4
    Is that a system level issue , java plugin issue?I'am confused with this error.
    Thanks sagar.

    870613 wrote:
    invalid context
    invalid pixel formatHm, seems like the Mac implementation of the Robot class is doing some bad initializations there. I can't be a 100% sure of course, but this smells like a bug to me. Are you sure you have the latest version of Java installed?

  • Robot class and positioning the cursor

    I have an application where I have a number of panels on the screen and using an editable field wish to enter coordinates to position the Cursor to on another panel.
    ie, using grid coordinates on a map. Using the robot class I am able to position the cursor on the other panel but as soon as I move the mouse the cursor jumps back to the original position on the screen where the first panel with the editable field was. It is like only a picture of the cursor was drawn at the new coordinates and the real cursor is still at the old podition. It is important to this application that if the cursor is moved it stays where it has been moved to and actually is there and not just appearing to be there. I am using jdk 1.3 on Intel Solaris 2.8. Any help on this issue would be helpful and appreciated

    Maybe you can use the mouse move event to position the mouse to where you had moved the cursor to.
    for example
    1.the mouse is at point 100,100
    2. you move the cursor from your code to point 0,0
    3. the user starts to move the mouse
    4. you code gets that event and repositions the cursor to the last place where it was, that is at 0,0

  • JavaFX drag events destroyed by window resize

    Hello,
    I've been having great success developing a drag-drop component for a JavaFX app, but I've run into an issue that has me completely stumped.
    Specifically, I create a component that can be dragged around inside an anchor pane.  That anchorpane is nested in a split pane, which is nested in another anchor pane (the control's root element).
    The issue can be described this way:
    Case #1:  If I start the application as a small window, I can reposition the control by dragging it around the screen as I please.
    Case #2: If I start the application and maximize the window, again, I can drag the control around the screen as I please.
    Case #3: If I start the application, drag the control around a bit, then resize the window, the drag event handling breaks as follows:
    1.  The control drag events will fire normally only within the bounds of the anchor pane's previous size.
    2.  The mouse cursor's drag icon changes as I pass in or out of those bounds
    I'm absolutely certain the anchorpane is resizing to match the parent window, otherwise Case #2 would not succeed.  I'm at a complete loss as to determine why the drag events don't fire within the bounds of the resized window after they've been fired within the bounds of it's previous size.
    Understand the mechanism I'm using to establish the drag handling:  Once the controller is instantiated and added to the scene, an event listener on the class's parentProperty fires to attach the drag event handling to the parent node.
    Previously, I was setting / clearing the drag handling on the parent node in the drag detection / drag dropped event handlers.  I had suspected that adding / removing drag events was causing the trouble and opted for this solution to ensure that the same event instance
    was being used each time.  Both methods have had the same result.
    If you want to see the UI in action, here's a youtube link (it does not demonstrate the problem I'm having):
    http://youtu.be/FJWRFN8xHFY
    Here's the code that I'm using, redacted for clarity:
    public class FileSystemNode extends AnchorPane {
        @FXML private AnchorPane fs_node_title;
        private FileSystemType mFsType;
        private Point2D mDragPoint;
        private EventHandler <MouseEvent> mNodeDragDetected;
        public FileSystemNode() {
            loadFxml();
            setId(mFsType.toString() + Double.toString(Math.random()));
        private void loadFxml() {
            FXMLLoader fxmlLoader = new FXMLLoader(
                    getClass().getResource("/FileSystemNode.fxml"));
            fxmlLoader.setRoot(this);
            fxmlLoader.setController(this);
            try {
                fxmlLoader.load();
                 parentProperty().addListener(new ChangeListener() {
                        @Override
                        public void changed(ObservableValue observable,
                                Object oldValue, Object newValue) {   
                            buildNodeDragHandlers();   
                            fs_node_title.setOnDragDetected(mNodeDragDetected);       
            } catch (IOException exception) {
                throw new RuntimeException(exception);
        public void relocateToPoint (Point2D p) {
            Point2D p2 = getParent().sceneToLocal(p);
            relocate (
                    (int) (p2.getX() - mDragPoint.getX()),
                    (int) (p2.getY() - mDragPoint.getY())
        public void buildNodeDragHandlers() {
            getParent().setOnDragOver(new EventHandler <DragEvent>() {
                //dragover to handle node dragging in the right pane view
                @Override
                public void handle(DragEvent event) {       
                    event.acceptTransferModes(TransferMode.ANY);
                    relocateToPoint(new Point2D( event.getSceneX(), event.getSceneY()));
                    event.consume();
            getParent().setOnDragDropped(new EventHandler <DragEvent> () {
                @Override
                public void handle(DragEvent event) {
                    event.setDropCompleted(true);
                    event.consume();
            //drag detection for node dragging
            mNodeDragDetected = new EventHandler <MouseEvent> () {
                @Override
                public void handle(MouseEvent event) {
                    mDragPoint = new Point2D(event.getX(), event.getY());
                            relocateToPoint(new Point2D(event.getSceneX(), event.getSceneY()));
                            ClipboardContent content = new ClipboardContent();
                            content.putString("node_drag");
                            startDragAndDrop (TransferMode.ANY).setContent(content);               
                            event.consume();                   

    Ok, I managed to reduce this even further to a single class that generates the entire application and drag events all at once.
    Copy / paste this into a new javaFX application to test it.  The case tests are:
    1.  drag/drop the "drag me!" label in the window's starting size
    2.  drag/drop the "drag me!" label only after resizing the window
    3.  Combine cases #1 and #2, dragging and dropping, resizing, then dragging and dropping again.
    In case 3, what happens for me is that the label cannot be dragged beyond the window's original bounds even though it's been resized to a larger size.
    If anyone with a better clue than I could try it and give me some thoughts, I'd certainly be appreciative.
    Thanks.
    import javafx.geometry.Point2D;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.input.ClipboardContent;
    import javafx.scene.input.DragEvent;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.input.TransferMode;
    import javafx.scene.layout.AnchorPane;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.Pane;
    import javafx.stage.Stage;
    import javafx.application.Application;
    import javafx.event.EventHandler;
    public class Main extends Application {
        private AnchorPane node_root;
        private BorderPane mRoot;
        @Override
        public void start(Stage primaryStage) {
            try {
                node_root = new AnchorPane();
                mRoot = new BorderPane();
                Scene scene = new Scene(mRoot,400,400);
                primaryStage.setScene(scene);
                primaryStage.show();
            } catch(Exception e) {
                e.printStackTrace();
            addFileSystemNode ();
            mRoot.setOnDragDone (new EventHandler <DragEvent>() {
                @Override
                public void handle(DragEvent event) {
    System.out.println ("Drag done");
                    event.consume();
        public static void main(String[] args) {
            launch(args);
        public final void addFileSystemNode () {
            Label node_title = new Label();
            node_title.setText("drag me!");
            node_root.getChildren().add (node_title);
            mRoot.getChildren().add (node_root);
            buildNodeDragHandlers();    
            node_root.setLayoutX(100.0);
            node_root.setLayoutY(100.0);
        public void relocateToPoint (Point2D p) {
            Point2D p2 = mRoot.sceneToLocal(p);
            node_root.relocate (
                    (int) (p2.getX()),
                    (int) (p2.getY())
        public void buildNodeDragHandlers() {
            mRoot.setOnDragOver(new EventHandler <DragEvent>() {
                //dragover to handle node dragging in the right pane view
                @Override
                public void handle(DragEvent event) {
                    System.out.println("parent node drag over" + " "  + ((Pane) event.getSource()).getId());
                    event.acceptTransferModes(TransferMode.ANY);
                    relocateToPoint(new Point2D( event.getSceneX(), event.getSceneY()));
                    event.consume();
            mRoot.setOnDragDropped(new EventHandler <DragEvent> () {
                @Override
                public void handle(DragEvent event) {
                    System.out.println("node drag dropped");            
                    event.setDropCompleted(true);
                    event.consume();
            //drag detection for node dragging
            node_root.setOnDragDetected( new EventHandler <MouseEvent> () {
                @Override
                public void handle(MouseEvent event) {
                    System.out.println("Drag detected");            
                    //begin drag ops
                    relocateToPoint(new Point2D(event.getSceneX(), event.getSceneY()));
                    ClipboardContent content = new ClipboardContent();
                    content.putString("node_drag");
                    node_root.startDragAndDrop (TransferMode.ANY).setContent(content);            
                    event.consume();                

  • Doing Shift-End using Robot class

    I am trying to use the Robot class to do a Shift-End in order to select the text in a window from the cursor to the end of the line. However, the following code only moves the cursor to the end of the line without selecting the text.
    robot.keyPress(KeyEvent.VK_SHIFT);
    robot.keyPress(KeyEvent.VK_END);
    robot.keyRelease(KeyEvent.VK_END);
    robot.keyRelease(KeyEvent.VK_SHIFT);
    Note that I have been able to make the following code work. So the problem with the code above does not seem to be with the Shift key per se or with the ordering of the statements.
    robot.keyPress(KeyEvent.VK_SHIFT);
    robot.keyPress(KeyEvent.VK_A);
    robot.keyRelease(KeyEvent.VK_A);
    robot.keyRelease(KeyEvent.VK_SHIFT);
    Any idea how to make the Shift-End work? I am using an XP PC.

    My ENTIRE code follows. Not surprisingly, the shiftEnd.actionPerformed gets a nullPointerException during execution. And being new to Java, I get the feeling I might be missing a whole bunch of stuff. For example, do I need to register for events? Do I need to generate a shift-End ActionEvent somehow? It is only the last 4 lines that are at issue here. Everything down to that point accomplishes what I want, i.e., position the mouse in a text window in the upper right-hand corner of my screen, move the cursor to the top of that window, then go down 5 lines. At that point, I want to do the shift-End to select all text in the line.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.KeyStroke;
    import javax.swing.JTextField;
    public class KeyStrokeTest {
    /** Creates a new instance of KeyStrokeTest */
    public KeyStrokeTest() {
    * @param args the command line arguments
    public static void main(String[] args)
    throws AWTException{
    Robot robot = new Robot();
    // Position mouse over Test Director test
    robot.mouseMove(600,300);
    // Press and release left mouse button to set focus in Test Director test
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    // Go to top of Test Director test
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_HOME);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyRelease(KeyEvent.VK_HOME);
    // Go down to first line of request
    for(int i=0;i<5;i++) {
    robot.keyPress(KeyEvent.VK_DOWN);
    robot.keyRelease(KeyEvent.VK_DOWN);
    robot.delay(1000);
    // Do a shift End
    KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_END,KeyEvent.VK_SHIFT);
    JTextField textComponent = new JTextField("String");
    ActionListener shiftEnd = textComponent.getActionForKeyStroke( keyStroke );
    shiftEnd.actionPerformed( null );

  • Why robot class doesnt get cursor

    i am using robot class , when i use createScreenCapture
    method it gets the everything on the screen but not the cursor.
    why? can i create i image that also get the cursor?
    many thanks

    MouseEvent provides a method:
    public Point getPoint()
    that returns the x,y position of the event relative to the source component.
    I guess it must be the archiect's view that the cursor is not a the screen, rather a device that points to the screen.
    -Merwyn
    Developer Technical Support
    Sun Microsystems
    http://www.sun.com/developers/support

  • Mouse dragged event with unexpected coordinates

    I am dragging the mouse on a half circle from the middle left to the top middle. This results in mouse events with the coordinates form (10,90) ->(100,10)
    Letting the mouse go and then dragging it further to the left, the coordinates in the of the event are similar than the starting point of the first mouse drag event.
    Can anyone shed some light on this peculiar behavior?

    First of, I have to apologize for the example not being as minimalistic as it might be, but on the plus side, I know now why this happens, I just don't know how to work around it.
    * To change this license header, choose License Headers in Project Properties.
    * To change this template file, choose Tools | Templates
    * and open the template in the editor.
    package javafxtest;
    import java.util.ArrayList;
    import javafx.application.Application;
    import javafx.beans.property.DoubleProperty;
    import javafx.beans.property.SimpleDoubleProperty;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.geometry.Dimension2D;
    import javafx.geometry.Point2D;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.StackPane;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Circle;
    import javafx.scene.shape.Polygon;
    import javafx.scene.shape.Rectangle;
    import javafx.scene.shape.Shape;
    import javafx.scene.transform.Rotate;
    import javafx.stage.Stage;
    * @author andi
    public class HandleRotation extends Application {
        private DoubleProperty currentRotation;
        private ArrayList<Double> angles;
        @Override
        public void start(Stage primaryStage) {
            currentRotation = new SimpleDoubleProperty(this, "currentRotation", 10);
            SteeringWheelGroup background = new SteeringWheelGroup(200);
            background.setManaged(false);
            Group g = new Group(background);
            final Point2D centerPoint = new Point2D(100, 100);
            angles = new ArrayList<>(3);
            angles.add(190.0);
            angles.add(270.0);
            angles.add(350.0);
            double step = (180.0 - 2 * currentRotation.doubleValue()) / (angles.size() - 1);
            int radius = 100;
            final int yTranslation = 15; // might be due to the labels
            Polygon handle = createHandle(centerPoint, radius, yTranslation);
            g.getChildren().add(handle);
            StackPane root = new StackPane();
            Scene scene = new Scene(g, 300, 250);
            primaryStage.setTitle("Handle Rotation!");
            primaryStage.setScene(scene);
            primaryStage.show();
         * Calculate the base point for the label. This is the point on the arc, matching the angle.
         * @param center point of the circle
         * @param radius radius of the circle
         * @param angle in degree in [0,180]
         * @return Point on the circle
        Point2D calculateBasePoint(Point2D center, double radius,
                double angle) {
            float newX = (float) (center.getX() + radius * Math.cos(Math.toRadians(angle)));
            float newY = (float) (center.getY() + radius * Math.sin(Math.toRadians(angle)));
            return new Point2D(newX, newY);
         * Create the polygon that represents the handle
         * @param centerPoint
         * @param radius
         * @return
        private Polygon createHandle(final Point2D centerPoint, int radius, final int yTranslation) {
            double baseAngle = 180;
            Point2D p1 = calculateBasePoint(centerPoint, radius, baseAngle - 5);
            Point2D p2 = calculateBasePoint(centerPoint, radius, baseAngle + 2);
            Point2D p3 = calculateBasePoint(centerPoint, radius*0.65, baseAngle + 2);
            Point2D p4 = calculateBasePoint(centerPoint, radius*0.65, baseAngle - 7);
            double[] points = {p1.getX(), p1.getY(), p2.getX(), p2.getY(), p3.getX(), p3.getY(), p4.getX(), p4.getY()};
                      Polygon polygon = new Polygon(points);
    //        polygon.setOpacity(0);
            polygon.setTranslateY(-yTranslation);
            final Rotate rotationTransform = new Rotate(currentRotation.doubleValue(), centerPoint.getX(), centerPoint.getY());
            polygon.getTransforms().add(rotationTransform);
            polygon.setOnMouseDragged(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    if (event.getY() < centerPoint.getY()) {
    System.out.println("Event: "+event);                   
                                                       Point2D point = new Point2D((float)event.getX(), (float)event.getY());
                        double newAngle = angleBetween2Lines(centerPoint, point);
                        if (newAngle < 0) {
                            newAngle = (90 + newAngle)+ 90;
    System.out.println("Set angle on mouse drag: "+newAngle);
                        if (newAngle < 10) {
                            newAngle = 10;
                        if (newAngle > 170) {
                            newAngle = 170;
                        currentRotation.set(newAngle);
            polygon.setOnMouseReleased(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    snapToNearestAngle();
                    rotationTransform.setAngle(currentRotation.doubleValue());
            return polygon;
         * Snap to the correct angle. Correct angle is angle belonging to the nearest label.
        void snapToNearestAngle() {
            double currentAngle = currentRotation.doubleValue() + 180;
            double currentMin = 360;
            int minIndex = 0;
    System.out.println("Current rotation is "+currentAngle);
            for (int i = 0; i < angles.size(); i++) {
                double angle = angles.get(i);
                double diff = Math.abs(angle - currentAngle);
                if (diff < currentMin) {
                    currentMin = diff;
                    minIndex = i;
    System.out.println("new minDifference at "+i+": "+diff);
            Double destinationAngle = angles.get(minIndex);
    System.out.println("DestinationAngle is "+currentAngle+" -> "+(destinationAngle - 180));
            if (destinationAngle < 180 + 10 || destinationAngle > 360 - 10) {
                throw new IllegalStateException("Angle is out of range: "+currentRotation.doubleValue()+" -> "+destinationAngle);
            currentRotation.set(destinationAngle - 180);
         * Calculate the angle between the vector horizontally to the left from the center
         * and the current point.
         * @param center point
         * @param point current point
         * @return angle in degree
        double angleBetween2Lines(Point2D center, Point2D point) {
            double slope2 = calculateSlope(center, point);
            double angle = Math.atan(slope2);
            if (point.getX() > center.getX()) {
                angle += Math.PI/2;
    System.out.println("Slope: "+slope2+" angle "+Math.toDegrees(angle));
            return Math.abs(Math.toDegrees(angle));
         * Caluculate the slope of the line defined by two points.
         * The first point is the center of a circle and the second
         * point roughly lies on the circle.
         * @param center point
         * @param point on the circle
         * @return slope of the connecting line.
        double calculateSlope(Point2D center, Point2D point) {
    System.out.println("center="+center+",point="+point);       
            double absSlope = Math.abs((point.getY() - center.getY()) / (point.getX() - center.getX()));
            if (point.getY() > center.getY()) {
                if (point.getX() > center.getX()) {
                    // bottom right
                    return -absSlope;
                } else {
                    // bottom left
                    return absSlope;
            } else {
                if (point.getX() > center.getX()) {
                    // top right
                    return absSlope;
                } else {
                    // top left
                    return -absSlope;
         * The main() method is ignored in correctly deployed JavaFX application.
         * main() serves only as fallback in case the application can not be
         * launched through deployment artifacts, e.g., in IDEs with limited FX
         * support. NetBeans ignores main().
         * @param args the command line arguments
        public static void main(String[] args) {
            launch(args);
       private class SteeringWheelGroup extends Group {
            public SteeringWheelGroup(int destinationWidth) {
                int topPadding = 0;
                Rectangle rect = new Rectangle(getImageWidth(), getImageWidth(), Color.RED);
                double scale = destinationWidth / rect.getWidth();
                rect.setScaleX(scale);
                rect.setScaleY(scale);
                Circle circle = new Circle(getImageWidth()/2, getImageWidth()/2, getImageWidth()/2, Color.BLUE);
                circle.setScaleX(scale);
                circle.setScaleY(scale);
                Group rotationGroup = new Group(/*rect,*/ circle);
                rotationGroup.setManaged(false);
                int width = getImageWidth();
                Rectangle clipRectangle = new Rectangle(0, 0, width, width / 2);
                Circle clipCircle = new Circle(width / 2, width / 2, width / 2);
                Shape clip = Shape.intersect(clipRectangle, clipCircle);
                rotationGroup.setClip(clip);
                this.getChildren().add(rotationGroup);
                //double h = calculateHeigthOverHorizon(angle, destinationWidth/2);
                //setTranslateY(-h+topPadding);
            public final int getImageWidth() {
                return 479;
    Here is how you can reproduce my effect:
    Grab the black handle
    Drag the mouse top and right until you approach the angle -90 (have an eye out on the console log)
    Let the mouse go: the handle will snap to 90 degree
    Grab the handle a second time and move further right
    You will see that the angle printed out do not match what you expect.
    Let the mouse go, the Handle snaps back to it's original position
    As the rotation does not happen around the polygon's center, I have to use a Rotaion effect, which is applied. While I can drag the shape from the rotated location the dragging is always measured from its base position.
    So what can I do to work around this?
    final Rotate rotationTransform = new Rotate(currentRotation.doubleValue(), centerPoint.getX(), centerPoint.getY());
    polygon.getTransforms().add(rotationTransform);
    If worse comes to worst, I can use a circular handle covering everything, then I can rotate around its center, but I would like to avoid this.

  • How to catch drag event in the title bar of a jframe

    Hi
    I want to catch the drag event in the title bar for jframe, because I have a few more window, dialogs, which I want to move along with my main window
    Thanks

    you can use a listener like tih one below...it works if you don't move to quickly.....
    class SynchroMover extends ComponentAdapter{
      private JFrame master;
      private JFrame[]slaves;
      private int currentX;
      private int currentY;
      public SynchroMover(JFrame master,JFrame[]slaves){
        this.master = master;
        this.slaves = slaves;
        currentX =(int) master.getLocation().getX();
        currentY =(int) master.getLocation().getY();
      public void componentMoved(ComponentEvent e){
        int dx = (int)master.getLocation().getX() - currentX;
        int dy = (int)master.getLocation().getY() - currentY;
        System.out.println(dx+" "+dy);
        for(int i=0;i<slaves.length;i++)
          slaves.setLocation((int)(slaves[i].getLocation().getX()+dx),(int)(slaves[i].getLocation().getY()+dy));
    currentX = (int)master.getLocation().getX();
    currentY = (int)master.getLocation().getY();
    the code isn't optimized...so you can probably do better

  • AWT Drag Events Not Registering

    Hi all,
    I have written up a small program (code is at the bottom) that uses the getToolkit().addAWTEventListener(new AWTEventListener() code. In it, it will listen for drag events. If it detects one, it will update a variable called currentPoint. Then I have a subclassed JPanel that everytime it paints, will display a rectangle at the current point.
    I then run the program and drag my mouse around for maybe 30 seconds. Things work 100% correct. After that though, it seems the AWTEventListener begins missing the events and the currentpoint doesn't update. This means the block that is following my mouse stops as my mouse cursor moves away during the drag. The point updates about a second later. So for example: If I am moving along the x-axis, the block follows me until say (10, 5) and then stops. My mouse then continues to move and it gets to (15,5) and then the block updates and jumps to that point. These actions steadily get worse and worse as I run the program.
    Does anyone have any idea what is occuring? I haven't given much thought but maybe the GC? You can also look at the output and there are no events processed during that time...
    Thanks,
    day
    Code:
    package main;
    import java.awt.AWTEvent;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.AWTEventListener;
    import java.awt.event.MouseEvent;
    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.Writer;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class DragWindow extends JFrame
         private Point currentPoint = null;
         private PaintPanel paintPanel;
         private boolean dragging = false;
         public DragWindow()
              super("Drag Test");
              paintPanel = new PaintPanel(this);
              this.getContentPane().add(paintPanel);
              try
                    final PrintWriter out
                      = new PrintWriter(new BufferedWriter(new FileWriter("dragData.txt")));
                   addWindowListener(new ExitListener(out));
                   setSize(1280, 1024);
                   setLocation(0, 0);
                   setVisible(true);
                   getToolkit().addAWTEventListener(new AWTEventListener()
                           public void eventDispatched ( AWTEvent e )
                                Point point = ((MouseEvent)e).getPoint();
                                currentPoint = point;
                                System.out.println("Parsed this: X: " + point.x + ". Y: " + point.y);
                                out.write("Parsed this: X: " + point.x + ". Y: " + point.y + "\n");
                                out.flush();
                                if(e.getID() == MouseEvent.MOUSE_DRAGGED)
                                     String data = "MOUSE_DRAGGED: Event: " + e.paramString();
                                     System.out.println(data);
                                     out.write(data);
                                     out.flush();
                                     dragging = true;
                                else if(e.getID() == MouseEvent.MOUSE_RELEASED)
                                     String data = "MOUSE_RELEASED: Event: " + e.paramString();
                                     System.out.println(data);
                                     out.write(data);
                                     out.flush();
                                     dragging = false;
                                repaint();
                      }, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK
              catch (FileNotFoundException e1)
                   e1.printStackTrace();
              catch (IOException e)
                   e.printStackTrace();
          * @return Returns the currentPoint.
         public Point getCurrentPoint ()
              return currentPoint;
          * @param currentPoint The currentPoint to set.
         public void setCurrentPoint ( Point currentPoint )
              this.currentPoint = currentPoint;
          * @return Returns the dragging.
         public boolean isDragging ()
              return dragging;
          * @param dragging The dragging to set.
         public void setDragging ( boolean dragging )
              this.dragging = dragging;
    package main;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JPanel;
    public class PaintPanel extends JPanel
         DragWindow window;
         public PaintPanel ( DragWindow window )
              this.window = window;
         public void paintComponent(Graphics g)
              super.paintComponents(g);
              Graphics2D g2d = (Graphics2D)g;
              if(window.getCurrentPoint() != null && window.isDragging())
                   Rectangle rectPoint = new Rectangle(window.getCurrentPoint().x, window.getCurrentPoint().y, 20, 20);
                   g2d.fill(rectPoint);
    package main;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.PrintWriter;
    import javax.swing.JFrame;
    /** A listener that you attach to the top-level Frame or JFrame of
    *  your application, so quitting the frame exits the application.
    *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    public class ExitListener extends WindowAdapter
         private JFrame frame;
         private PrintWriter outi;
         public ExitListener(PrintWriter o)
              outi = o;
          * @return Returns the frame.
         public JFrame getFrame ()
              return frame;
          * @param frame The frame to set.
         public void setFrame ( JFrame frame )
              this.frame = frame;
         public void windowClosing(WindowEvent event)
              outi.close();
              System.exit(0);     
    }

    i ran your code on my Pc and do not encounter the problem that you have described. The rectangle always follows my mouse when I drag, however, it isnt at the current point of the mouse. It stays a constant value below it.
    Also, GC is unnecessary. java auotmatically gc's when needed.
    I am unsure what may be wrong for you since your app seems to work fine for me, even after a steady 1.5 - 2 mins of dragging.

  • I can't be the only person who has this problem - when a month ends on a Saturday I can't drag events into the next month and instead have to cut and paste - a real pain in the butt. I thought there was something called "scroll" but I can't find that

    I can't be the only person who has this problem with iCal- when a month ends on a Saturday I can't drag events into the next month and instead have to cut and paste - a real pain in the butt. I thought there was something called "scroll" but I can't find that.

    Yeah that works, but, it involves a click on the event, a click on edit, a click on the date, keystrokes, plus, since you can't see the next month you have to have a calendar in front of you so as to put it to the right date. It's easier just to cut it and advance the month and paste it, once you are in the right month you can move it around helter skelter willy nilly no problems. Although now that you mention it I will try it, maybe it is easier than cut and paste as I don't really care about the date, as long as it gets moved into the right month I can drag it around all I want.

  • Robot class in Windows Vista

    Hello,
    It seems like there are problems with the java Robot class in Windows Vista.
    Did anyone encounter them?
    Thanks

    I didn't get your response, but I will try to explain myself.
    I have a problem with a program that I wrote that uses the Robot class and doesn't run well on Vista.
    I think that the operation system isn't letting it to control the mouse/keyboard: The program didn't crash,
    Simply didn't move the mouse although it was supposed to.
    I searched google for relevant information and the only relevant result I found was the link I posted.
    That link doesn't help me because in order to view the answer I have to pay money.
    I posted it because I thought that another description of the problem might help to understand it.

  • Calling Portal event from ABAP class

    Hi Experts,
    I need a following clarificatrion, Please help,
    1. Is it possible to call a webdynpro method from a normal ABAP class?
    2. If no, we need a functionality of a class 'CL_WDR_HTTP_EXT_MIME_HANDLER' having method 'DO_DOMAIN_RELAX_HTML'.
    Is there any alternative method which can be used in ABAP having the same functionality.
    3. Is there any ways with which we can call portal event from ABAP class?
    Thanks,
    Shabir

    >1. Is it possible to call a webdynpro method from a normal ABAP class?
    I wouldn't necessarily recommend this approach. You shouldn't try to trigger events or any of the standard WDDO* methods from outside the WD Component itself.  That said, you can pass the object reference (like the WD_COMP_CONTROLLER object reference or the View Object Reference) into methods of normal classes.  Be careful if you are finding yourself calling a lot of your added methods from outside WD.  This is probably a sign that these methods should be in the Assistance Class or some other Class functioning as a Model Object.
    >2. If no, we need a functionality of a class 'CL_WDR_HTTP_EXT_MIME_HANDLER' having method 'DO_DOMAIN_RELAX_HTML'.
    Is there any alternative method which can be used in ABAP having the same functionality.
    What exactly do you want to do here?  Do you just want to get the relaxation script?  For what purpose?  You should never need to inject the relaxation script into WDA. 
    >3. Is there any ways with which we can call portal event from ABAP class?
    To what purpose.  Do you just want to delegate the triggering of the event that is inside WD Component to be called from a class?  If so you can pass the portal API object reference into a class from the WD Component.  However this only works while running within WD.
    How is this class used?  Are you running in WD?  Are you trying to generate some HTML code that runs in the portal independent of WD?

Maybe you are looking for