Dealing with AffineTransform mouse driven rotation

Hi there,
I'm implementing the mouse control to navigate through an image representing a map. Pan and zoom where trivial operations, but I'm getting in trouble when trying to rotate the BufferedImage.
I actually can perform the rotation, but because the map coordinate system gets rotated too. I have applied a trigonometric correction when performing a pan after a rotation. This was the hard part... my problem is that I have inverted the axis when panning, so dragging the mouse to the bottom of the canvas becomes a horizontal translation if we had a rotation by PI rads.
Because original Java code is pretty big, I have coded a simple example that pans, zooms or rotates a square.
The magic happens here:
def performPan(self,diff):
        xa = diff.x*lang.Math.cos(self.theta)+diff.y*lang.Math.sin(self.theta)
        ya = -diff.x*lang.Math.sin(self.theta)+diff.y*lang.Math.cos(self.theta)
        diff.x -= (diff.x - xa)
        diff.y -= (diff.y - ya)
        center = self.canvas.squareCenter()
        # if self.theta != 0: self.transform.rotate(-self.theta, center.x, center.y)       
        self.transform.translate(diff.x, diff.y)
        #if self.theta != 0: self.transform.rotate(self.theta, center.x, center.y)
    def performZoom(self,diff):     
          zoomLevel = 1.0+0.01*diff.y;
          if zoomLevel <= 0:
              zoomLevel = 0
          center = self.canvas.windowCenter()          
          self.transform.scale(zoomLevel, zoomLevel)
    def performRotation(self,diff):
         angleStep = diff.y * 0.1
         self.theta += diff.y
         self.theta %= 2*lang.Math.PI
         center = self.canvas.squareCenter()
         self.transform.rotate(angleStep, center.x, center.y)
    def toWindowCoordinates(self,diff):
        try:
            self.transform.inverseTransform(diff,diff)
        except:
            print "error en window coordinates"I have already tried changing diff.x and diff.x sign, and commenting that trigonometric correction and uncommeting the lines concatenating two rotations surrounding the translation without sucess.
Please, I'd appreciate some feedback. Brainstorms are welcome. :-)
Thanks, Vicente.
The full code:
from javax import swing
from java import awt, lang;
class Listener(swing.event.MouseInputAdapter):
    def __init__(self,subject):
        self.offset = awt.geom.Point2D.Double()
        self.anchor = awt.geom.Point2D.Double()
        self.canvas = subject
        self.transform = subject.transform
        self.rectangle = subject.rectangle
        self.theta = 0.0
    def mousePressed(self,e):
        self.anchor.x = e.getX()
        self.anchor.y = e.getY()
        self.offset.x = e.getX()
        self.offset.y = e.getY()
    def mouseDragged(self,e):
        self.offset.x = e.getX()
        self.offset.y = e.getY()
        diff = awt.geom.Point2D.Double()   
        tx = self.offset.x - self.anchor.x
        ty = self.offset.y - self.anchor.y
        diff.x = tx
        diff.y = ty      
        self.anchor.x = self.offset.x
        self.anchor.y = self.offset.y
        class Painter(lang.Runnable):
            def __init__(self,canvas, listener):
                self.canvas = canvas
                self.listener = listener
            def run(self):
                if e.isControlDown():
                    self.listener.performRotation(diff)
                elif swing.SwingUtilities.isLeftMouseButton(e):       
                    self.listener.performPan(diff)       
                if swing.SwingUtilities.isRightMouseButton(e):
                    self.listener.performZoom(diff)
                self.canvas.repaint()
        work = Painter(self.canvas, self)
        swing.SwingUtilities.invokeLater(work)
    def mouseReleased(self,e):
        self.color = awt.Color.red
        self.canvas.repaint()
    def performPan(self,diff):
        xa = diff.x*lang.Math.cos(self.theta)+diff.y*lang.Math.sin(self.theta)
        ya = -diff.x*lang.Math.sin(self.theta)+diff.y*lang.Math.cos(self.theta)
        diff.x -= (diff.x - xa)
        diff.y -= (diff.y - ya)
        center = self.canvas.squareCenter()
        if self.theta != 0: self.transform.rotate(-self.theta, center.x, center.y)       
        self.transform.translate(diff.x, diff.y)
        if self.theta != 0: self.transform.rotate(self.theta, center.x, center.y)
    def performZoom(self,diff):     
          zoomLevel = 1.0+0.01*diff.y;
          if zoomLevel <= 0:
              zoomLevel = 0
          center = self.canvas.windowCenter()          
          self.transform.scale(zoomLevel, zoomLevel)
    def performRotation(self,diff):
         angleStep = diff.y * 0.1
         self.theta += diff.y
         self.theta %= 2*lang.Math.PI
         center = self.canvas.squareCenter()
         self.transform.rotate(angleStep, center.x, center.y)
    def toWindowCoordinates(self,diff):
        try:
            self.transform.inverseTransform(diff,diff)
        except:
            print "error en window coordinates"
class Canvas(swing.JPanel):
    def __init__(self):
        self.rectangle = awt.geom.Rectangle2D.Double(0,0,50,50)
        self.transform = awt.geom.AffineTransform()   
        self.wcenter = awt.geom.Point2D.Double()
        self.rcenter = awt.geom.Point2D.Double()
        listener = Listener(self)
        swing.JPanel.addMouseMotionListener(self,listener)
        swing.JPanel.addMouseListener(self,listener)
    def paintComponent(self,g2d):
        self.super__paintComponent(g2d)
        g2d.setTransform(self.transform)
        g2d.fill(self.rectangle)
    def windowCenter(self):
        if self.wcenter.x == 0 or self.wcenter.y == 0:
            self.wcenter.x = self.getHeight()/2.0
            self.wcenter.y = self.getWidth()/2.0     
        return self.wcenter
    def squareCenter(self):
        if self.rcenter.x == 0 or self.rcenter.y == 0:
            self.rcenter.x = self.rectangle.getBounds2D().height/2.0
            self.rcenter.y = self.rectangle.getBounds2D().width/2.0       
        return self.rcenter
frame = swing.JFrame(   title="test",
                        visible=1,
                        defaultCloseOperation = swing.JFrame.EXIT_ON_CLOSE,
                       preferredSize = awt.Dimension(400,400),
                        maximumSize = awt.Dimension(800,600),
                        minimumSize = awt.Dimension(200,200),
                        size = awt.Dimension(500,500)
frame.add(Canvas(), awt.BorderLayout.CENTER)
frame.pack()

I forgot to mention that the example is written in
Jython, because the Java was pretty big, but it is
legible bu a Java programmer. :-)It's legible, but most of us w/out a jython compiler would have to re-write the code if we wanted to try it out. That may hurt your chances of getting a useful response (as opposed to my useless responses). ... Or it might not.
Good luck!
/Pete

Similar Messages

  • How to deal with the mouse events when the thread is running

    Hi everybody,
    I have a problem with my program.
    Now I want to present a picture for some time in the Canvas,then automatically clear the screen, but when the user press the mousebutton or keybutton, I want to stop the thread and clear the screen.
    How can I receive the mouse event when the thread is running?
    Thanks,

    I use my code in a GUI applet.
    I try to use the code tag, it's the first time.
                   Image im=sd.getStimulus(obj);
                   if(pos==null){
                        g.drawImage(im, (w-im.getWidth(null))/2,(h-im.getHeight(null))/2,null);
                   }else{
                        g.drawImage(im, pos.x,pos.y,pos.w,pos.h,null);
                   try{
                        sleep(showtime);
    //                    Thread.sleep(showtime);
                   }catch(InterruptedException e){}
                   if(pos==null){
                        g.clearRect((w-im.getWidth(null))/2,(h-im.getHeight(null))/2,im.getWidth(null),im.getHeight(null));
                   }else{
                        g.clearRect(pos.x,pos.y, pos.w, pos.h);
                   }

  • Performance issues with Motion (position, scale, rotate) and GTX 590

    I'm experiencing performance issues with my Premiere Pro CC when I scale, position or rotate a clip in the program monitor.
    I have no performance issues with playback! It's only, when i move something with the mouse or by changing the x,y-values of Position in the Motion-Dialog in video effects.
    Premiere then lags terribly and updates the program monitor only about once per second - this makes it very difficult and cumbersome to work and position things.
    On a second Premiere installation on my laptop, performance is fine and fluid - allthough it doesn't have GPU support and is a much slower computer.
    I'm pretty sure this has somehow to do with my graphic card, which is a Nvidia GTX 590.
    I was told by the support, that it is actually a dual graphic card, which is not supported/liked by Premiere.
    The thing is, until the latest Premiere update, I did not have performance issues at all with this card.
    I also read on the forum that others with the GTX 590 did not experience any problems with it
    So where does this come from?
    There is no change in performance whether or not I activate Mercury Playback Engine GPU acceleration.
    I also tried deactivating one of the 2 gpus, but there also was no change.
    Does anyone else know this problem and has anyone a solution?
    I'm running Premiere CC on a Win 7 64bit engine, Nvidia GTX 590, latest driver (of today),

    I am suffering from the same phenomenon since I updated just before christmas, I think.
    I am hardly able to do scaling, rotating and translating in the program monitor itslef - whil motion has been highlighted in teh effect controls.
    In the effect controls I can scale, rotate etc however.
    Also I have noticed there is a yellow box with handles in teh program monitor. I remember it was white before.
    I cannot figure out what to change in my preferences. What has happened?
    best,
    Hans Wessels
    Premiere CC
    Mac Pro OSX 10.7.5
    16 GB 1066 MHz DD3
    2 X NVIDIA GeForce GT 120 512 MB

  • My brand new Macbook PRO crashed completely after it went through the iOS 10.7.4 update, I lost everything and Apple just wants to replace the HD and let me deal with the hassle.

    Last Thursday May 10th I received a prompt from the Automatic Update to update the iOS to Ver. 10.7.4, set the start and was watching the progress when it stopped with an error message saying that it was not able to update, right below there was a buttom "RESTART", pressed the buttom and waited to re-boot.....That was the end of my computer, somehow the update crashed my HD beyond recover, it would only show the gray screen with Apple logo in the center and kept beeping, BEEP BEEP BEEP.....PAUSE.....BEEP BEEP BEEP.....PAUSE.....on and on and on and it never past that.
    Friday May 11 I took it to a retailer where I received the bad news that the HD was crashed and the teck couldn't even try to copy anything from it as it couldn't locate it. I checked iCloud on a hope that all my stuff would be there but new surprise, iCloud didn't kept all of my stuff as it was programmed to.
    Now here is the funny part, the tech from the retailer informed me that the only thing they could do was to order a new HD for my 4 months old Macbook and that the time to have my computer back will be at least 15 days, now that is the funny part, I fail to understand why do I have to suffer the hassle of loosing all my data plus wait at least 15th days to have my computer back (meanwhile loose work) on a problem caused by Apple, PROBLEM, not machine defect, clearly my computer had no problem untill I followed the procedure to update.
    On Saturday May 12 I contacted Local Apple Support (I have failed to mention that I live in Brasil) and they informed me that what the dealer said was the only thing that could be done, too bad for me if I lost everything, going to loose several days of work and whenever I receive my computer back will have to re-construct all my life and deal with the forever lost data.....DEAL WITH IT
    After a couple of discussion with Apple Support and the Dealer, I made my decision to take the Macbook to the dealer today for repair and meanwhile I'm opening a case with the Brazilian Justice to have Apple honor with all the trouble and hassle that it is causing me, it's said that I have to take this type of action as I'm a very fan of Apple and it's products, have had several iPods, iPhones, Macbooks, Keyboards, Mouses, Apple TV, etc.....This i the first time I have a problem with a Apple product and got a taste of the "Apple Care", it seems like Apple is more concerned on seeling products then keeping long time customers happy.
    One last thing, today when I was at the dealer to drop my computer for repair, the Technician informed me that he also had a computer crashed and the HD erase on Sunday May 13th in the same way of mine, after the update everything was gone, also he said that we were not the only ones, iPads and iPhones were going trough the same situation, update causing complete breakdown.
    WORD OF ADVISE, BE 1000% SURE THAT YOU HAVE EVRYTHING BACKED UP BEFORE YOU GO THROUGH AN UPDATE.

    rvalezin wrote:
    If I need to back-up every hour of my life in order to be able to save everything from something like this I won´t do anything else.....at least we should be able to trust that Apple tests this updates so situations like this won´t happen.
    That's exactly what Time Machine does for you.  It backs up every hour, so you don't have to.  While it is backing up, you keep on working.  Time Macvhine came with your Mac and you chose not to use it.
    The 10.7.4 update did not cause your hard disk to fail.  Hard disk fail due to mechanical causes.  They are extremely reliable, but that doesn't mean every hard disk will last a long time.  Your mileage WILL vary!
    If you are dependent on your computer and the data stored on it, then you should make sure you have AT LEAST two copies of all data and probably three or four.  You should use at least two means of backing up in case the backup software has a problem.  And you should consider having a backup computer if you live in an area where replacement takes too long (whatever too long is for your business).
    Apple hardware and software is very, very good.  You have documented your experience of this.  But NO hardware or software is perfect.  You also have experience of this.
    It is YOUR responsibility to ensure that your system is set up to protect your data and availability of computing resources.

  • How do I know if my mouse is bad?  I'm having trouble highlighting text with my mouse, model A1152

    How do I know if my mouse needs to be replaced or if it something else?  I am having increasing trouble highlighting text, it either won't hold the highlighting, or it won't highlight . . . making it impossible to create a link in my emails, to delete text, or copy and paste.
    I have an iMac that is about 4 years old and the mouse that came with it uses a USB port to connect.
    Thanks for any information or suggestions.

    Is it one of those with a little moving/rotating ball on the bottom of it? Have you ever taken that out and cleaned it and the area holding it? It could be dust/dirt in there. I always used a QTip slightly moistened with alcohol.

  • How to set the size of a control with the mouse ?

    hi all,
    i am writing a sort of ide (editor which creates applets very easy....) - for this purpose i need some hints from you guys:
    of course i need to create some controls like buttons...
    no prob - i am able to create buttons and place them at any place.
    BUT WHAT ABOUT THE SIZE ?
    ok, i have some ideas to realize this but what i want is a thick border arround the control with spots at each corner - when i place the cursor at one of these spots, my mouse cursor should change and it must be able to change the size of the control (while pressing and moving the mouse - you all know that from any ide).
    so how to do that?
    go on brains!!!
    THANX,
    andi

    I thought about creating dynamically resizable components, but gave it up as the effort seems too much for the benefit. I did a search for info on it and found a lot of people who wanted to do it, but not any who had actually done it completely. Here's some of my thoughts on the subject. You are right on about creating 'sizing handles', it seems to me the way to do this is to create your own container for any component (extend JPanel?) which can switch between no border and your new sizing border at some event. You will need to respond to mouse clicks on this border and follow the 'drag' event to find out where it was dropped. The java drag/drop events probably won't be of any use to you because each component will need an event handler. You need to catch them all.
    Finally, you need to figure out how to interact with some LayoutManager or write your own. Most LayoutManagers want to do their own resizing and you will have to deal with this. For example, GridBagLayout will not only resize all of the other components on the affected row and column, but unless you resize the other components, you won't be able to drag the top higher or the left lefter?

  • What's the deal with bluetooth mice ?

    What's the deal with bluetooth mice ? I've never heard of any model yet that didn't come with loads of complain... (I've done my research) ... isn't there one that just works fine and that will for a few years like a standard mouse ?
    I would really like one with my macbook, any recommendation, something portable, that matches well my hardware would be nice.
    Or should I just wait until bluetooth mice technology works flawlessly ? What about you ?
    Francis.

    I've had a Macally BtMouseJr for a couple of years now, it's fairly basic but every time I've tried to replace it with a "better' one I've had to come back because of lock ups, losing the mouse altogether, slow response, random movements et al.
    Therefore the BtMouseJr is the ONLY one I can actually recommend (I retract my prvious recommendation of the Sony vaio mouse - it's nice but it doesn't always work and eats batteries) wholeheartedly.
    see it here.

  • Since I upgraded to Moutain Lion I'm dealing with wifi problems : no connection or random connection

    Since I upgraded to Moutain Lion I'm dealing with wifi problems : no connection or random connection. With  OS X Lion wifi was OK.

    So, Darrall, it seems to be fixed.  Mind you, this has happened through a seemingly unrelated, but hopefully replicable sequence of events.  You be the judge.
    I went to my other login account, which as it happens is also an admin account.  Voila, the secondary click worked fine.  So I returned to my primary account, where I did the following:
    First, I unpaired the trackpad.  then I remembered I needed something to move the mouse with, so I re-paired the magic mouse I'd had before.  I thought I'd turned off the trackpad, but apparently not, so the computer re-paired it automatically. None of this had any immediate effect, as you'd imagine.
    Then I went to Mission Control in Preferences. There, I deselected "Show dashboard as a space", and in the hotcorners, I deselected Mission Control from the bottom left, where it had been. I didn't replace it.
    Now, my secondary click works. Uh huh. I was suspicious that it might have more to do with Mission Control and/or Dashboard than the trackpad, only because I'd beaten that horse till my arm hurt and this was all I could think of. 
    Never did I imagine this would get fixed short of creating a new login account and somehow copying everything - since I didn't know what was wrong, I could easily have copied the error too - so I'm very pleased and relieved.  If you haven't fixed yours yet, try this.  Let me know what happens!

  • How should one deal with sub-projects?

    Hello to all!
    Let me first clarify my title-question.
    On my current project I faced software malfunction [FCPX quitting] when I reached 17 minutes of building the video on the timeline. [As a reference, allow me to call this 17-minute part of the video in making as the main project.]
    Remembering from an earlier thread [? Mr. Russ being the contributor], I opted to continue the project as a separate project which I seek to call as the sub-project  Now even this sub-project is of a 14 minute duration and I have need to start a sub-project 2.
    I would now like to be guided as to how to deal with these sub-projects while editing the video and after finishing the project.
    Firstly, while editing. My present plan is to complete the project's video utilising as many sub-projects as needed, and then add the sub-projects to the main project. This done, I intend to add voiceover for the completed project. During this process, my questions are this...how do I add the sub-projects onto the main project? If I select and copy/paste the sub-project, it gets added as 'connected clips'...this is okay if one can export the project as such. But, when a voiceover has to be added, further retiming of the clips are called for and at this stage problems arise. Now, as I am writing this, it is striking me that I could make this added sub-project as a secondary storyline, get done with the retiming after the voiceover is added, and export the project. Have not done this before and would like guidance from senior contributors in this issue.
    Secondly, when the project is exported and is being archived, do I need to have all the sub-projects or delete them to save drive-space?
    Thanks in advance.
    Have a great day.
    Dr. Somanna

    Thanks Karsten for this further instructions. The present project I am working on is being done as a race against time. Faced a problem when dealing with a stack of generator clips one upon the other and each clip being given different commands regarding changes in position and rotation. Beyond the 17 minute mark, one click upon the parameter in the inspector window, and the application quit. When this quitting became a regular feature, I just remembered a thread in which one contributor wrote that he usually divides his projects into 10 minute bits before making up the whole project. Not willing to spend time further on this problem, being in a very 'creative frame mode' I simply continued working upon the project by starting up a 'sub-project'.
    Regards and take care.
    Dr. Somanna

  • I have inserted a mini cd in my Mac Book Pro and cannot eject it. I have tried re-starting with F12 depressed and re-starting with the mouse pad depressed.

    I have inserted a mini cd in my cd drive but the drive did not detect it; I am unable to eject the cd. I have tried re-starting with F12 depressed and also re-starting with the mouse pad depressed.
    I am in a country where I belive there is no Apple support - Azerbaijan.
    Apart from a tin opener, any other methods for extracting the mini cd.
    I only found out that mini cds are not suitable after inserting this one and then reading 2 help manuals!!!

    Take it to a place that repairs computers if you're not close to any apple authorized dealer.
    You user guide clearly states that you can not use smaller CDs in your Macbook.
    Lesson learned.  Hopefully a repair shop can get it out for you.
    Do not try to take it out yourself.  You might cause more damage than good to your macbook.
    Good luck.

  • Safari update - problem with magic mouse

    Hi all, I recently installed safari update to 5.1 (6534.50) on a mabbook pro OS X 10.6.8. Ever since update, I've been experiencing the problem with safari reloading pages and kicking me out of websites that use flash player (back to log-in screen). I can deal with that by using another browser, however the update has really messed up my magic mouse. At first, every time I put my macbook to sleep or shut it off, the mouse would stop responding when I woke the mac up. I would have to disconnect the mouse and reconnect. But this was really eating up my batteries, so this morning I shut the mouse off when I put the mac to sleep. Now it won't connect at all. Anybody have any suggestions? Thanks in advance for your help!

    Thanks Carolyn and Barry,
    I did what Carolyn suggested - moving the .plist file into the trash. I have not resetting the PRAM or SMC yet.
    When I go to system preferences>Bluetooth, I get a screen that says:
    Bluetooth power is off. To use Bluetooth, first you must turn it on. (Note - my mouse is turned on)
    Both ON and DISCOVERABLE are checked.
    In the middle of the screen, it says No Devices (Set Up New Device...)
    When I select set up new device, it finds my device and attempts to pair but is unsuccessful.
    Resetting the SMC and PRAM scares me. After reading the links that Carolyn provided, I remembered another weird issue I had with my mac shortly before the update and mouse issue. For some reason, my clock suddenly became out of sync and I was on a 2000 date. I got an error message and reset the clock manually. Could this be the cause of my mouse issue? I feel like every step I've taken to get my mouse working again has made the problem just a little bigger!
    Thanks again for helping me!
    Judy

  • Stop reverse scrolling with microsoft mouse

    Please accept my apologies if this question has already been asked and answered.  I searched but could not find the answer in this forum.  I recently purchased a Mac Mini computer running Lion OS.  I use a microsoft mouse and keyboard that came complete with drivers for the MAC.  I am experiencing two intermittent problems relating to mouse action and cursor.
    1.  The first problem is with reverse scrolling.  Somehow, and I can't recall how, I managed to disable reverse scrolling.  However, intermittently my computer reverts to reverse scrolling.  Often I am able to fix the problem by rebooting the Mac.  On other occassions this does not work.  I have researched the issue online and have read the articles about turning off reverse scrolling in the mouse and track pad sections of System Preferences.  However, this option is not available presented when I access these windows.
    2.  The second problem deals with cursor size.  I use my mac mini a a media center connected to my TV.  To make the navigation easier I have made the cursor as large as possilbe using System Preferences - Universal Access - Mouse Tab.  However, frequently the cursor reverts back to the minimum size on its own.  When I access the appropriate section of System Preferences I note that, according to my configuration, the cursor should be maximized.  I can re-establish the maximum size my making the cursor smaller and then making it bigger or conversely by rebooting the Mac.
    Any assistance on these two matters would be greatly appreciated.
    Many thanks,
    Wayne

    I have issue #1 randomly reversing scrolling direction, what is wrong? My system Mac Mini with Microsoft Mouse / Keyboard.

  • DoDragDrop oddity with Right Mouse Button

    Hi all,
    More experimentation - today with Drag & Drop.
    Everything seems fine when performing this with the left mouse button, but when initiating this from WPF
    with the right mouse button it appears to trigger the PreviewDrop event on the originating object.
    I've tried intercepting QueryContinueDragHandler, which is fired and is having an Action set of Continue - all to no avail.
    Much time with google shows no examples of people using the right mouse button with DoDragDrop, and a single query on this forum in September with someone having a similar problem.  No replies to that thread - hopeing for more luck today!
    So, has anyone successfully initiated a system based Drag/Drop using the right mouse button?  In this case I'm working with a ListView, but I suspect that is fairly irrelevant.
    Events occuring with Right Mouse Button depressed (and dragging a small way) are:
    Call to: System.Windows.DragDrop.DoDragDrop
    Callback: DropSource_ContinueDragEventHandler
    Callback: DropTarget_PreviewDragEnter
    Callback: DropSource_ContinueDragEventHandler
    Callback: DropTarget_PreviewDrop
    With the Left Mouse Button:
    Call to: System.Windows.DragDrop.DoDragDrop
    Callback: DropSource_ContinueDragEventHandler
    Callback: DropTarget_PreviewDragEnter
    Callback: DropSource_ContinueDragEventHandler
    Callback: DropSource_ContinueDragEventHandler
    Callback: DropSource_ContinueDragEventHandler
    etc...
    Anyone aware of any issues in this area?
    Thanks,
    Glyn
    PS: The behaviour is different if dragging something from another application / desktop to a drop target, so it appears to be related to the originating side of things. ie, there is no problem when dragging an object from the desktop or similar.

    Hmm - seem to have found the problem - it is related to the ContinueDragEventHandler!
    Here is a suitable handler for dealing with Left & Right mouse button drags
    You can activate it using:
    DragDrop.AddQueryContinueDragHandler(this, QueryContinueDragHandler);
    private void QueryContinueDragHandler(Object source, QueryContinueDragEventArgs e)
        e.Handled = true;       
        // Check if we need to bail
        if (e.EscapePressed)
            e.Action = DragAction.Cancel;       
            return;
        // Now, default to actually having dropped
        e.Action = DragAction.Drop;
        if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.None)
            // Still dragging with Left Mouse Button
            e.Action = DragAction.Continue;
        else if ((e.KeyStates & DragDropKeyStates.RightMouseButton) != DragDropKeyStates.None)
            // Still dragging with Right Mouse Button
            e.Action = DragAction.Continue;

  • "Slow" Leopard with bonus mouse issues!

    I have a Mac Mini at work, and ever since upgrading it to Snow Leopard, it's been driving me insane. I haven't had time to deal with it, so I've gotten used to all the annoying performance issues I'm having. Simply put, Snow Leopard is super slow, or "dopey" as I like to say. Every thing I do (EVERYTHING) happens slowly. Here are a few examples of what I'm dealing with. Switching between apps takes too long, from many seconds to minutes for an app to "wake up" again. When I click Print in Numbers, the print window takes up to a minute to appear, and then another 10-20 seconds before I can actually click print. As an added bonus, the mouse does a couple of "nifty" things on a regular basis. The first thing it does is it "locks" the left-click as if I'm holding down the button. I have to click it again to "release" it, so a lot of the time, I'm clicking the mouse three times just to do one click. The downward scroll also stops working intermittently. Now take the goofy mouse and mix it with the dopey leopard, and you've got yourself a wacky guessing-game! Is the mouse button locked or am I just waiting for the dopey leopard to wake up? Let's click again and see what happens! Maybe the pinwheel will show up, or maybe an open window will move halfway off the screen. Or better yet, maybe I'll delete two emails instead of just the one I wanted to! Weee! And by the way, the mouse issues happen whether I'm using a wired USB Mighty Mouse, wireless Mighty Mouse, or a Magic Mouse. Every once in a while, I get brief glimpses of the real Mac Mini - everything zips along beautifully for a couple minutes - but then it goes back to "dopey" mode. I don't even know who this Mac is anymore. My seven-year-old iMac at home works better than this thing. It doesn't do much anymore, but at least it shows me some respect.

    How full is the hard drive?
    Try resetting the PRAM. Info here:
    http://docs.info.apple.com/article.html?artnum=2238

  • Draw with single mouse click, help me!!!!

    I am using this code - as you understood from it- to paint with the mouse click.
    please help me either by completing it or by telling me what to do.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Hello extends JFrame{
         Graphics g;
         ImageIcon icon = new ImageIcon("hello.gif");
         public Hello(){
              super("Hello");
              setSize(200, 200);
              addMouseListener(
                   new MouseAdapter(){
                        public void mouseClicked(MouseEvent e){
                             icon.paintIcon(Hello.this, g, e.getX(), e.getY());
                             g.fillRect(10, 40, 10, 80);
                             JOptionPane.showMessageDialog(Hello.this, e.getX() + ", " + e.getY());
                             //repaint();
         // i have tried to place this listener in the paint method, but no way out.
              setVisible(true);
         public void paint(final Graphics g){
              this.g = g;
              icon.paintIcon(this, g, 100, 50);
         public static void main(String[] args){
              new Hello();
    **

    You can't save a graphics object like that and then paint on it.
    What you need is to use a BufferedImage, paint on that, and then paint that to the screen.
    See my paintarea class. You are welcome to use + modify this class as well as take any code snippets to fit into whatever you have but please add a comment where ever you've incorporated stuff from my class
    PaintArea.java
    ===========
    * Created on Jun 15, 2005 by @author Tom Jacobs
    package tjacobs.ui;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import javax.swing.SwingUtilities;
    import tjacobs.MathUtils;
    * PaintArea is a component that you can draw in similar to but
    * much simpler than the windows paint program.
    public class PaintArea extends JComponent {
         BufferedImage mImg; //= new BufferedImage();
         int mBrushSize = 1;
         private boolean mSizeChanged = false;
         private Color mColor1, mColor2;
         static class PaintIcon extends ImageIcon {
              int mSize;
              public PaintIcon(Image im, int size) {
                   super(im);
                   mSize = size;
         public PaintArea() {
              super();
              setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
              addComponentListener(new CListener());
              MListener ml = new MListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
         public void paintComponent(Graphics g) {
              if (mSizeChanged) {
                   handleResize();
              //g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
              g.drawImage(mImg, 0, 0, null);
              //super.paintComponent(g);
              //System.out.println("Image = " + mImg);
              //System.out.println("Size: " + mImg.getWidth() + "," + mImg.getHeight());
         public void setBackground(Color c) {
              super.setBackground(c);
              if (mImg != null) {
                   Graphics g = mImg.getGraphics();
                   g.setColor(c);
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
         public void setColor1(Color c) {
              mColor1 = c;
         public void setColor2(Color c) {
              mColor2 = c;
         public Color getColor1() {
              return mColor1;
         public Color getColor2() {
              return mColor2;
         class ToolBar extends JToolBar {
              ToolBar() {
                   final ColorButton fore = new ColorButton();
                   fore.setToolTipText("Foreground Color");
                   final ColorButton back = new ColorButton();
                   back.setToolTipText("Background Color");
                   JComboBox brushSize = new JComboBox();
                   //super.createImage(1, 1).;
                   FontMetrics fm = new FontMetrics(getFont()) {};
                   int ht = fm.getHeight();
                   int useheight = fm.getHeight() % 2 == 0 ? fm.getHeight() + 1 : fm.getHeight();
                   final BufferedImage im1 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = im1.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2, useheight / 2, 1, 1);
                   g.dispose();
                   //im1.setRGB(useheight / 2 + 1, useheight / 2 + 1, 0xFFFFFF);
                   final BufferedImage im2 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im2.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 1, useheight / 2 - 1, 3, 3);
                   g.dispose();
    //               im2.setRGB(useheight / 2 - 1, useheight / 2 - 1, 3, 3, new int[] {     0, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0}, 0, 1);
                   final BufferedImage im3 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im3.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 2, useheight / 2 - 2, 5, 5);
                   g.dispose();
    //               im3.setRGB(useheight / 2 - 2, useheight / 2 - 2, 5, 5, new int[] {     0, 0, 0xFFFFFF, 0, 0, 
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0, 0, 0xFFFFFF, 0, 0}, 0, 1);
                   //JLabel l1 = new JLabel("1 pt", new ImageIcon(im1), JLabel.LEFT);
                   //JLabel l2 = new JLabel("3 pt", new ImageIcon(im2), JLabel.LEFT);
                   //JLabel l3 = new JLabel("5 pt", new ImageIcon(im3), JLabel.LEFT);
                   brushSize.addItem(new PaintIcon(im1, 1));
                   brushSize.addItem(new PaintIcon(im2, 3));
                   brushSize.addItem(new PaintIcon(im3, 5));
                   //brushSize.addItem("Other");
                   add(fore);
                   add(back);
                   add(brushSize);
                   PropertyChangeListener pl = new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent ev) {
                             Object src = ev.getSource();
                             if (src != fore && src != back) {
                                  return;
                             Color c = (Color) ev.getNewValue();
                             if (ev.getSource() == fore) {
                                  mColor1 = c;
                             else {
                                  mColor2 = c;
                   fore.addPropertyChangeListener("Color", pl);
                   back.addPropertyChangeListener("Color", pl);
                   fore.changeColor(Color.BLACK);
                   back.changeColor(Color.WHITE);
                   brushSize.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ev) {
                             System.out.println("ItemEvent");
                             if (ev.getID() == ItemEvent.DESELECTED) {
                                  return;
                             System.out.println("Selected");
                             Object o = ev.getItem();
                             mBrushSize = ((PaintIcon) o).mSize;
                   //Graphics g = im1.getGraphics();
                   //g.fillOval(0, 0, 1, 1);
                   //BufferedImage im1 = new BufferedImage();
                   //BufferedImage im1 = new BufferedImage();
         protected class MListener extends MouseAdapter implements MouseMotionListener {
              Point mLastPoint;
              public void mouseDragged(MouseEvent me) {
                   Graphics g = mImg.getGraphics();
                   if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                        g.setColor(mColor1);
                   } else {
                        g.setColor(mColor2);
                   Point p = me.getPoint();
                   if (mLastPoint == null) {
                        g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        //g.drawLine(p.x, p.y, p.x, p.y);
                   else {
                        g.drawLine(mLastPoint.x, mLastPoint.y, p.x, p.y);
                        //g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        double angle = MathUtils.angle(mLastPoint, p);
                        if (angle < 0) {
                             angle += 2 * Math.PI;
                        double distance = MathUtils.distance(mLastPoint, p) * 1.5;
                        if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4 || Math.abs(Math.PI - angle) < Math.PI / 4) {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x, mLastPoint.y + i, p.x, p.y + i);
                                  g.drawLine(mLastPoint.x, mLastPoint.y - i, p.x, p.y - i);
    //                              System.out.println("y");
    //                              System.out.println("angle = " + angle / Math.PI * 180);
                        else {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x + i, mLastPoint.y, p.x + i, p.y);
                                  g.drawLine(mLastPoint.x  - i, mLastPoint.y, p.x - i, p.y);
    //                              System.out.println("x");
    //                    System.out.println("new = " + PaintUtils.printPoint(p));
    //                    System.out.println("last = " + PaintUtils.printPoint(mLastPoint));
                        //System.out.println("distance = " + distance);
                        //Graphics2D g2 = (Graphics2D) g;
                        //g2.translate(mLastPoint.x + mBrushSize / 2, mLastPoint.y);
                        //g2.rotate(angle);
                        //g2.fillRect(0, 0, (int) Math.ceil(distance), mBrushSize);
                        //g2.rotate(-angle);
                        //g2.translate(-mLastPoint.x + mBrushSize / 2, -mLastPoint.y);
    //                    g.setColor(Color.RED);
    //                    g.drawRect(p.x, p.y, 1, 1);
                   mLastPoint = p;
                   g.dispose();
                   repaint();
              public void mouseMoved(MouseEvent me) {}
              public void mouseReleased(MouseEvent me) {
                   mLastPoint = null;
         private void handleResize() {
              Dimension size = getSize();
              mSizeChanged = false;
              if (mImg == null) {
                   mImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                   Graphics g = mImg.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
              else {
                   int newWidth = Math.max(mImg.getWidth(),getWidth());
                   int newHeight = Math.max(mImg.getHeight(),getHeight());
                   if (newHeight == mImg.getHeight() && newWidth == mImg.getWidth()) {
                        return;
                   BufferedImage bi2 = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = bi2.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
                   g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
                   g.dispose();
                   mImg = bi2;
         public JToolBar getToolBar() {
              if (mToolBar == null) {
                   mToolBar = new ToolBar();
              return mToolBar;
         private ToolBar mToolBar;
         public static void main (String args[]) {
              PaintArea pa = new PaintArea();
              JPanel parent = new JPanel();
              parent.setLayout(new BorderLayout());
              parent.add(pa, BorderLayout.CENTER);
              pa.setPreferredSize(new Dimension(150, 150));
              parent.add(pa.getToolBar(), BorderLayout.NORTH);
              WindowUtilities.visualize(parent);
         protected class CListener extends ComponentAdapter {
              public void componentResized(ComponentEvent ce) {
                   mSizeChanged = true;
    }

Maybe you are looking for