Mouse Drag in JDialog produces Mouse Enter & Mouse Exit events in JFrame.

Hi, all.
Do I have a misconception here? When I drag the mouse in a modal JDialog, mouseEntered and mouseExited events are being delivered to JComponents in the parent JFrame that currently happens to be beneath that JDialog. I would not have expected any events to be delivered to any component not in the modal JDialog while that JDialog is displayed.
I submitted this as a bug many months ago, and have heard nothing back from Sun, nor can I find anything similar to this in BugTraq.
Here is sample code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
* This class demonstrates what I believe are TWO bugs in Mouse Event handling in Swing
* 1.1.3_1, 1.1.3_2, 1.1.3_3, and 1.4.0.
* 1) When a MODAL JDialog is being displayed, and the cursor is DRAGGED from the JDialog
*    into and across the parent JFrame, Mouse Enter and Mouse Exit events are given to
*    the parent JFrame and/or it's child components.  It is my belief that NO such events
*    should be delivered, that modal dialogs should prevent ANY user interaction with any
*    component NOT in the JDialog.  Am I crazy?
*    You can reproduce this simply by running the main() method, then dragging the cursor
*    from the JDialog into and across the JFrame.
* 2) When a MODAL JDialog is being displayed, and the cursor is DRAGGED across the JDialog,
*    Mouse Enter and Mouse Exit events are given to the parent JFrame and/or it's child
*    components.  This is in addition to the problem described above.
*    You can reproduce this by dismissing the initial JDialog displayed when the main()
*    method starts up, clicking on the "Perform Action" button in the JFrame, then dragging
*    the cursor around the displayed JDialog.
* The Mouse Enter and Mouse Exit events are reported via System.err.
public class DragTest
    extends JFrame
    public static void main(final String[] p_args)
        new DragTest();
    public DragTest()
        super("JFrame");
        WindowListener l_windowListener = new WindowAdapter() {
            public void windowClosing(final WindowEvent p_evt)
                DragTest.this.dispose();
            public void windowClosed(final WindowEvent p_evt)
                System.exit(0);
        MouseListener l_mouseListener = new MouseAdapter() {
            public void mouseEntered(final MouseEvent p_evt)
                System.err.println(">>> Mouse Entered: " + ((Component)p_evt.getSource()).getName() );
            public void mouseExited(final MouseEvent p_evt)
                System.err.println(">>> Mouse Exited: " + ((Component)p_evt.getSource()).getName() );
        JPanel l_panel1 = new JPanel();
        l_panel1.setLayout( new BorderLayout(50,50) );
        l_panel1.setName("JFrame Panel");
        l_panel1.addMouseListener(l_mouseListener);
        JButton l_button = null;
        l_button = new JButton("JFrame North Button");
        l_button.setName(l_button.getText());
        l_button.addMouseListener(l_mouseListener);
        l_panel1.add(l_button, BorderLayout.NORTH);
        l_button = new JButton("JFrame South Button");
        l_button.setName(l_button.getText());
        l_button.addMouseListener(l_mouseListener);
        l_panel1.add(l_button, BorderLayout.SOUTH);
        l_button = new JButton("JFrame East Button");
        l_button.setName(l_button.getText());
        l_button.addMouseListener(l_mouseListener);
        l_panel1.add(l_button, BorderLayout.EAST);
        l_button = new JButton("JFrame West Button");
        l_button.setName(l_button.getText());
        l_button.addMouseListener(l_mouseListener);
        l_panel1.add(l_button, BorderLayout.WEST);
        l_button = new JButton("JFrame Center Button");
        l_button.setName(l_button.getText());
        l_button.addMouseListener(l_mouseListener);
        l_panel1.add(l_button, BorderLayout.CENTER);
        JButton l_actionButton = l_button;
        Container l_contentPane = this.getContentPane();
        l_contentPane.setLayout( new BorderLayout() );
        l_contentPane.add(l_panel1, BorderLayout.NORTH);
        JPanel l_panel2 = new JPanel();
        l_panel2.setName("JDialog Panel");
        l_panel2.addMouseListener(l_mouseListener);
        l_panel2.setLayout( new BorderLayout(50,50) );
        l_panel2.add( new JButton("JDialog North Button"),  BorderLayout.NORTH  );
        l_panel2.add( new JButton("JDialog South Button"),  BorderLayout.SOUTH  );
        l_panel2.add( new JButton("JDialog East Button"),   BorderLayout.EAST   );
        l_panel2.add( new JButton("JDialog West Button"),   BorderLayout.WEST   );
        l_panel2.add( new JButton("JDialog Center Button"), BorderLayout.CENTER );
        final JDialog l_dialog = new JDialog(this, "JDialog", true);
        WindowListener l_windowListener2 = new WindowAdapter() {
            public void windowClosing(WindowEvent p_evt)
                l_dialog.dispose();
        l_dialog.addWindowListener(l_windowListener2);
        l_dialog.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        l_dialog.getContentPane().add(l_panel2, BorderLayout.CENTER);
        l_dialog.pack();
        Action l_action = new AbstractAction() {
            { putValue(Action.NAME, "Perform Action (open dialog)"); }
            public void actionPerformed(final ActionEvent p_evt)
                l_dialog.setVisible(true);
        l_actionButton.setAction(l_action);
        this.addWindowListener(l_windowListener);
        this.pack();
        this.setLocation(100,100);
        this.setVisible(true);
        l_dialog.setVisible(true);
}(Too bad blank lines are stripped, eh?)
Thanks in advance for any insights you may be able to provide.
---Mark

I guess we can think of this as one problem. When mouse dragged, JFrame also (Parent) receives events. If i understood correctly, what happens here is, Modal dialog creates its own event pump and Frame will be having its own. See the source code of Dialog's show() method. It uses an interface called Conditional to determine whether to block the events or yield it to parent pump.
Here is the Conditional code and show method code from java.awt.dialog for reference
package java.awt;
* Conditional is used by the EventDispatchThread's message pumps to
* determine if a given pump should continue to run, or should instead exit
* and yield control to the parent pump.
* @version 1.3 02/02/00
* @author David Mendenhall
interface Conditional {
    boolean evaluate();
/////show method
    public void show() {
        if (!isModal()) {
            conditionalShow();
        } else {
            // Set this variable before calling conditionalShow(). That
            // way, if the Dialog is hidden right after being shown, we
            // won't mistakenly block this thread.
            keepBlocking = true;
            if (conditionalShow()) {
                // We have two mechanisms for blocking: 1. If we're on the
                // EventDispatchThread, start a new event pump. 2. If we're
                // on any other thread, call wait() on the treelock.
                if (Toolkit.getEventQueue().isDispatchThread()) {
                    EventDispatchThread dispatchThread =
                        (EventDispatchThread)Thread.currentThread();
                       * pump events, filter out input events for
                       * component not belong to our modal dialog.
                       * we already disabled other components in native code
                       * but because the event is posted from a different
                       * thread so it's possible that there are some events
                       * for other component already posted in the queue
                       * before we decide do modal show. 
                    dispatchThread.pumpEventsForHierarchy(new Conditional() {
                        public boolean evaluate() {
                            return keepBlocking && windowClosingException == null;
                    }, this);
                } else {
                    synchronized (getTreeLock()) {
                        while (keepBlocking && windowClosingException == null) {
                            try {
                                getTreeLock().wait();
                            } catch (InterruptedException e) {
                                break;
                if (windowClosingException != null) {
                    windowClosingException.fillInStackTrace();
                    throw windowClosingException;
    }I didn't get exactly what is happening but this may help to think further

Similar Messages

  • Not detecting mouse exit events

    I'm developing a Java application that implements an 'auto-hide' functionality - similar to that of the Office Shortcut bar - such that when the mouse moves outside of the application frame the window auto-hides. I'm using the Mouse Exit event to detect when the mouse moves outside of the the application frame and then I 'hide' the window (or rather resize it to 2 pixels high) so I can then detect the Mouse Entered event to restore the window.
    This works OK but occasionally if I move the mouse quick enough the exited event isn't detected and the window doesn't always hide.
    Are there any other ways of detecting if the mouse moves outside of the application frame (so I can also trigger my 'hide' function) without relying on other events such as windowLostFocus.
    Thanks,
    Richard.

    I have one suggestion:
    Check that the component that you use to monitor mouse exit and enter events has at least one pixel visible from all sides (most layout managers allow a border (not a Border class or subclass) that is not occupied by child subcomponent).
    For example if you will place some other component in container directly so some side then mouse enter and exit events will be fired on that component and not on the container.

  • Mouse Drag Issues.

    I've been having problems with using my mouse to "click and drag". I'm pretty sure that is is not a hardware issue. It happens in multiple apps and general OS navigation. For example I will attempt to click and drag a folder into another. I wont be able to because the mouse wont stop the drag after I let go of the button. The folder icon gets stuck to the mouse pointer, I have to force quit and relaunch Finder using the keyboard's enter key because I cant use the mouse click to force quit.
    The same thing happens in other applications. ie. Im browsing the web. Occasionally when I click a link, an outline drag will get stuck to the mouse. Then I can't click anywhere else to make use of the browser until I force quit it and start over. This happened in an unsaved photoshop document too. In that case I got a large outline drag box stuck to the mouse, and the entire app froze up. Couldn't save with keyboard or mouse, had to force quit and loose my work. That's when I started looking to fix this problem and came here.
    Im using the wireless logitech s530 keyboard/mouse combo. I've been using it without a hitch for the last 6 months that I've had my Mac.
    Also a side note, I had a fatal error screen (which I've never seen before) for the operating system a couple days ago, for which it instructed me to hold the power button to restart. I don't know if its related but it happened around the same time this mouse/crashing problem started.
    Any help would be greatly appreciated.
    -Bob Funk

    This sounds like a driver issue. Have you tried reinstalling your mouse's driver or checking for an update on the Logitech website? I'd recommend visiting their downloads site and install the latest driver for your mouse. Hopefully that will work. One way to test this would be to boot into safe mode by holding "shift" at bootup. When the system boots see if the mouse behaves the same way, and then restart the computer normally to restore normal non-safemode function.

  • Mouse dragging events in NSWindow and NSView

    Hi, I have built and application that uses a single window that contains multiple components within it. The main component of the window is a custom NSView subclass that contains a number of CALayers. I want to be able to move these layers around the NSView subclass based on the mouseDown, mouseDragged, and mouseUp events entered by the user. I can detect and process mouse events fine within the NSView subclass, however, whenever I drag the mouse within the NSView subclass right after a mouseDown event, the WHOLE WINDOW will move. I do not want that to happen, that is, when I am dragging the mouse within my NSView subclass, I do not want the whole window to move. I want my CALayers, within the NSView, to move according to the mouse events that I am correctly tracking in the NSView subclass. I will very much appreciate any suggestions. Thank you very much in advance.

    Thank you very much for your response. Your tip is very useful. What I did before was change the window type in Interface Builder: replace the textured window with a regular window. This solved the problem, however, I could not find the property that needed to be adusted to control the window behavior. I learned something useful with your tip. Thanks again.

  • [SOLVED] Thunar 1.6 doesn't drag-and-drop with the right mouse button

    Hallo all.
    It might be something I've done (though I did delete my ~/.config/Thunar directory before upgrading), but Thunar doesn't let me drag-and-drop with the right mouse button, thus stopping me from copying something instead of moving it, etc. Has anyone else had that too?
    Last edited by GordonGR (2012-12-28 14:34:20)

    Joel wrote:
    anonymous_user wrote:Is it supposed to be with the right-mouse button? I always thought drag and drop was done with the left button?
    Could be right-hand user
    Come on! Read what GordonGR wrote!
    Microsoft Windows, Nautilus, the Haiku Tracker, and probably many other file managers have a feature where, when you right-click or middle-click and drag an icon to a new location, a pop-up menu appears and asks what you'd like to do (Move, Copy, Link). I thought I used to use this feature in Thunar too but it seems to have stopped working in recent versions. Has anyone else had any experience with it?
    EDIT: Here's random blogger talking about the feature in an older version of Thunar: http://jeromeg.blog.free.fr/index.php?p … and-tricks So that's good, I wasn't just imagining the feature.
    Last edited by drcouzelis (2012-12-12 03:45:05)

  • Move tool issue : Command key + mouse dragging for moving any layer not working in PS CC

    I'm trying to move a layer within the document by holding command key and mouse dragging (mouse cursor not above the layer) is not working at all while using move tool. Suddenly this functionality stopped working. Now I have to place my cursor on layer to be move and drag with mouse. Also pressing command key changing auto select option from layer to group.
    Please help.

    Usually when a tool is not working as expected, a Reset of that tool might be the answer.
    Select the move tool in the toolbox,
    Go to the move tool icon on the top left of the screen (just above the toolbox in its' Option bar) and Ctrl-click on it to get the Reset menu.
    Click on Reset Tool.

  • Cannot scroll drop downs, or drag and drop files/folders with mouse

    I cannot scroll drop downs (I can click them, but I can't choose anything) or drag files or folders with the mouse or touch pad, but it works fine when I use my Wacom tablet. It's super frustrating. Help!

    P.S. I've narrowed the problem down to being related to the game Diablo III. If I restart my machine, it works fine again. Until I play Diablo. Totally lame.

  • Mouse Drag is not working in Applets

    In our application we are using applets in containing in IFRAMES in IE to display different type of graphs and animations etc. User can open/close these Applets and iframes to navigate from one data view to other. During this navigation sometimes mouse drag event stops and all drag related operations like scrolls etc stops responding to drag operations in all applets in same JVM.
    My investigation shows that swing component hierarchy gets corrupted somehow and this exception is thrown
    EventMulticaster.eventDispatched(Toolkit.java:2244)
         at java.awt.Toolkit.notifyAWTEventListeners(Toolkit.java:2203)
         at java.awt.Component.dispatchEventImpl(Component.java:4528)
         at java.awt.Container.dispatchEventImpl(Container.java:2099)
         at java.awt.Component.dispatchEvent(Component.java:4460)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4603)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4255)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
         at java.awt.Container.dispatchEventImpl(Container.java:2085)
         at java.awt.Component.dispatchEvent(Component.java:4460)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    peerComponents in Container class is returning null on call to getLocationOnScreen that causes this exception.
    I fixed the issue in awt library but ORACLE license terms don't allow redistribution of modified version of awt.
    Please help me fix this issue in applet code or suggest me to bypass license restrictions.
    Thanks in advance!
    Luqman

    877922 wrote:
    peerComponents in Container class is returning null on call to getLocationOnScreen that causes this exception.
    I fixed the issue in awt library but ORACLE license terms don't allow redistribution of modified version of awt.Something Oracle do allow is to raise a bug report. On that report they invite you to post a work-around or fix. That would be the place to put the fix you have devised. Oracle will (supposedly) fix it, then you (and everyone else) can enjoy the fix as a free upgrade in the next version.
    They also offer 'support contracts' (AFAIU) in which you might pursue your own immediate fixes. But raise the bug report anyway.

  • Bug: lost selection after a mouse drag

    To reproduce:
    - select many entities in a diagram
    - move them a bit via mouse drag
    what happens
    - the group loses focus. If you've been unfortunate, you've selected non-contiguous entities (via CTRL-click over) and now they are somewhere in the diagram, behind other entities, etc. and you can't move them back because you lost the group selection.
    what should happen
    - after the move, the group is still selected
    Edited by: T. on Jun 6, 2011 5:06 AM

    I have seen this too. I discovered that once they are all selected (ctrl-A) you need to be careful to then click inside one of the entities to do the drag otherwise it does get messed up. Undo fixes it sometimes. Other times I have exited without saving to get back to a previous arrangement.

  • Clicking mouse after closing JDialog sends event to last component (1.1.8)

    There seems to be a bug in Java 1.1.8 that I'm looking for a workaround.
    I have a JButton on a JFrame that brings up a modal JDialog when you click it. After closing the dialog, if you click on the JFrame without moving the mouse, it will click the button on the frame that was last clicked, even if the mouse is not over the button.
    Steps to reproduce:
    1. Use the mouse to click on the button on the frame to bring up the dialog.
    2. Close the dialog with the mouse or keyboard and don't move the mouse at all. (Note that the mouse should be over the JFrame at this point, but not over the frame's button.)
    3. Click the mouse again.
    Result:
    This causes the button on the frame to be clicked.
    It seems as if the frame thinks that the mouse pointer is located where it was when the dialog came up.
    Does anyone know how to prevent this from happening or a workaround?

    We are using 1.1.8 because our product has to run on Mac OS 8.x - 9.x (and this is the latest JRE supported by these platforms).
    When I say don't move the mouse, what I mean is when closing the dialog, if you don't move the mouse, it doesn't matter where the mouse pointer is, as long as it's over the frame. When you click it, the last button to get clicked will be clicked again. It's as if the frame thinks that the mouse hasn't moved since the dialog came up. This isn't a focus problem because if I set the focus on another control after opening the dialog (by calling requestFocus()), this problem still happens. I can also tab to another control after closing the dialog, but when clicking the mouse it still clicks the last button that was clicked. It's as if the frame needs to reset where the mouse position is when it becomes activated.

  • Consuming extra mouse drag events?

    Hi,
    In my mouse drag listener, there is a bit heavy processing that can take slightly long time (doing some real time computation). If I move the mouse fast, then there would be a long pause before processing catch up.
    So my question is that if it is possible to remove some mouse drag events in the queue s.t. my computation only takes on the latest drag event.
    I tried java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().peekEvent(), but it always returns null.
    Anyone could give a hint? Thanks a lot.

    This heavy processing should be done in a new thread and not the event thread. If the event thread is busy processing, it's not going to be able to respond to drag events. Once you do that, it would be easy to set a flag in that thread to notify it to stop processing and start with new values.

  • Default implementation of mouse drag event?

    Is there any Default implementation of mouse drag event?
    Say if the developer does not override and implement mouse drag event, still when the frame is dragged, the frame gets repainted itself in the new position. It indicates some default implementation of mouse drag event, but am unable to find out where it has been implemented.
    Why bother when everything works fine? I have a requirement to move my non-modal dialog when the frame is being dragged to another location. I tried adding mousemotionlistener to the frame, to the panel inside a frame, but the event does not reach my custom implementation of mousedrag event.
    Any clues?

    Moving the frame is a different listener: ComponentListener; add one to the frame. The frame's window decorations are OS territory, so I'm not sure if there's system dependence. I seem to vaguely remember some systems sending an event only after done moving, while others send the event as the frame moves.

  • Mouse drag, hand tool not working at all!

    So I've installed Photoshop CC 2014 and Illustrator CC 2014 on my computer, started a new file but only found that any action that includes mouse dragging - creating shapes, hand tool, pen tool - do not work at all, everything just do not respond, when creating a shape it will treat it as if I have clicked once (which pops out the create rectangle window for size input..), the same situation happens to Photoshop as well (perhaps all Adobe CC software). I've been trying everything that have been suggested on the forum (some from the links below): removing all other software at the background (spotify, 1password, etc). Also I've tried with using different sets of keyboard and mouse, either wired and wireless, still no luck. One situation that finally works is that all software work perfectly fine in safe mode, then I rebooted back to normal mode, try killing any background process that was not running in safe mode, still...not working at all...
    References:
    (Illustrator CS6) Spacebar stops working seemingly randomly
    Spacebar Shortcut: Hand Tool Not Showing and Not Working
    Illustrator gets stuck on hand tool
    My computer specs:
    Windows 7 Pro 64-bit
    Intel Core i3-4130 3.4Ghz
    4GB RAM

    wecon,
    You could try to reinstall using the full three step way:
    Uninstall, run the Cleaner Tool, and reinstall.
    http://www.adobe.com/support/contact/cscleanertool.html

  • 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.

  • Scroll JTable in Scrollpane with mouse drag

    Hello developers !
    I'm trying to make a scrollable Jtable. The table have to be scrollable with the mouse drag event. But I have a "flashing" Problem. I can catch the Mouse events from the table (I'm listener the mouse motion and mouse events).
    When I receive a new mouse drag event, I set the new position from the viewport. The problem is, that the Table flash:
    For example:
    I drag the mouse to the bottom of the table. The mouse "y" position have to increase, but it doesn't:
    first motion event position (10, 10)
    second motion event position (10, 15)
    third motion event position (10, 12)
    etc..
    The position of the mouse event are in relation of the component position. I think, the problem is that I change the position of the view port and than the new mouse event is "on a wrong reference".
    Could someone help me? How could I make a work around for this Problem?

    I have the solution... it is easy.
    I post the solution because i spent two days making working around (changing viewport position other scrollbar values, etc).
    You dont need to implement the Autoscroll interface. The Autoscroll interface is for Drag and Drop classes.
    The key was the function JTable#scrollRectToVisible....
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class ScrollableTableFrame extends JFrame{
      protected ScrollableTable table;
      public ScrollableTableFrame() {
        super("Scrollable Table");
        setSize(600, 300);
        String data[][] = new String[40][40];
        String header[] = new String[40];
        for(int i = 0; i < 40; i++){
          header[i] = "Header " + i;
          for(int j = 0; j < 40; j++){
            data[i][j] = "(" + i + ", " + j +")";
        ScrollableTable table = new ScrollableTable(data, header);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        JScrollPane sp = new JScrollPane();
        sp.getViewport().setBackground(table.getBackground());
        sp.getViewport().add(table);
        getContentPane().add(sp, BorderLayout.CENTER);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 400);
        setVisible(true);
      public static void main(String args[]){
        new ScrollableTableFrame();
    class ScrollableTable extends JTable{
      private Point firstPressedPoint;
      public ScrollableTable(Object rowData[][], Object columnNames[]){
        super(rowData, columnNames);
      protected void processMouseEvent(MouseEvent e){
        int id = e.getID();
        switch(id) {
          case MouseEvent.MOUSE_PRESSED:
            firstPressedPoint = e.getPoint();
            break;
          case MouseEvent.MOUSE_RELEASED:
            firstPressedPoint = null;
            break;
          case MouseEvent.MOUSE_CLICKED:
          case MouseEvent.MOUSE_EXITED:
          case MouseEvent.MOUSE_ENTERED:
        super.processMouseEvent(e);
      protected void processMouseMotionEvent(MouseEvent e){
        if(e.getID() == MouseEvent.MOUSE_DRAGGED){
          Rectangle r = getVisibleRect();
          Point p = e.getPoint();
          int dx = (firstPressedPoint.x-p.x);
          int dy = (firstPressedPoint.y-p.y);
          Rectangle aRect = new Rectangle(r.x + dx, r.y + dy , r.width + dx, r.height + dy);
          scrollRectToVisible(aRect);
    }P.S.: jarshe, thank you for your help !!

Maybe you are looking for

  • Win Vista 32 bit to windows 7 64 bit how to back up firefox bookmarks, passwords?

    Currently on Vista 32 bit OS. Using FRESH HDD I'm switching to Windows 7 64 bit... Want to back up everything to external hard drive to put on new HDD. '''''FIREFOX passwords, bookmarks, cookies, maybe even settings?''''' 1) Able to backup 32 bit fir

  • Where are keyword files located and how do I get them into lightroom 4?

    I have upgraded from lightroom 3 to lightroom 4.  In many cases the keywords are missing - sort of. When I click on a single photo, the keywords don't show up.  If I select a bunch of photos, the keywords show up as a group.  Why aren't they listed f

  • Split AVI by date

    Working in Premier CS3, Win XP. I have a bunch of captured video, both captured from a DV camera and old hi-8 camera. I'd like to get it broken up by the dates so I can store by date. I'm also pretty new at this video stuff so bear with me. When I op

  • How to execute ABAP QUERY.

    Hi all,         I know how to create ABAP QUERY using transactions SQ01,SQ02 and SQ03.But after creating it how to and where to use it. Rgds, Tkp

  • Lumia 720 black- OS update issue and Apps download...

    I am using Lumia 720 Black, Everythings seems to be oky, but I cannot download apps from store, though I congfigured my Microsoft account. Nor I am able to download new software updates. Help me..