The best way to make zoom over a Graphic2D object

Hi to all!
I'm reading severals webs that describe the way to make zoom using Java2D. I'm working with an object Graphic2D and I want let the user to zomming in over the image, clicking the left mouse button and make zoom out clicking the right mouse button. I'm trying to make this using the method "scale()" of Graphic2D class, but I don't understand how it really works and I don't know if I have choised the best way to implement the zoom function. I let you a piece of code that I think sould do that I have said, why doesn't it works?
public class zoom extends JPanel implements MouseListener, MouseMotionListener{
    public static JFrame window = new JFrame();
    Graphics2D g2;
    public static void main(String[] args) {
        zoom internalPanel = new zoom();
        internalPanel.setBorder(BorderFactory.createTitledBorder("Zoom test"));
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setPreferredSize(new Dimension(500, 500));
        window.setLayout(new FlowLayout(FlowLayout.CENTER));
        window.add(internalPanel);
        window.pack();
        window.setVisible(true);
    public zoom(){  
        setPreferredSize(new Dimension(500, 500));
        addMouseListener(this);
        addMouseMotionListener(this);
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g2 = (Graphics2D) g;
        Dimension d = getSize();
        Image mImagen = createImage(500, 500);
        Graphics2D offG = (Graphics2D) mImagen.getGraphics();
        offG.setColor(Color.white);
        offG.fill(new Rectangle2D.Double(0, 0, d.width, d.height));
        g2.drawImage(mImagen, 0, 20, null);
        g2.setColor(Color.blue);
        Ellipse2D ellipse = new Ellipse2D.Double(100.0d, 100.0d, 100.0d, 100.0d);
        g2.fill(ellipse);
    public void mouseClicked(MouseEvent e) {
        if (e.getButton()==1){
            g2.scale(10.0, 10.0);
        if (e.getButton()==3){
            g2.scale(-10.0, -10.0);
    public void mousePressed(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mouseDragged(MouseEvent e){}
    public void mouseMoved(MouseEvent e){}
}Thanks for read.
Edited by: Daniel.GB on May 1, 2008 5:02 PM

zoom makes centering the zoomed image over the mouse pointer
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class ZoomTest2 extends JPanel implements MouseListener,
                                                 MouseMotionListener {
    Image mImagen;
    Point loc;
    double scale = 1.0;
    double scaleInc = 0.1;
    double MIN_SCALE = 0.25;
    final int WIDTH  = 500;
    final int HEIGHT = 500;
    public ZoomTest2(){  
        addMouseListener(this);
        addMouseMotionListener(this);
    public Dimension getPreferredSize() {
        Dimension d = new Dimension();
        d.width  = (int)(scale*WIDTH);
        d.height = (int)(scale*HEIGHT);
        return d;
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        Dimension d = getSize();
        if(mImagen == null) {
            mImagen = createImage(WIDTH, HEIGHT);
            Graphics2D offG = (Graphics2D) mImagen.getGraphics();
            offG.setColor(Color.white);
            offG.fill(new Rectangle2D.Double(0, 0, d.width, d.height));
            offG.dispose();
            loc = new Point(WIDTH/2, HEIGHT/2);
        AffineTransform orig = g2.getTransform();
        // Center the scaled image under the mouse pointer.
        double x = loc.x - scale*WIDTH/2;
        double y = loc.y - scale*HEIGHT/2;
        g2.translate(x, y);
        g2.scale(scale, scale);
        g2.drawImage(mImagen, 0, 0, null);
        g2.setColor(Color.blue);
        Ellipse2D ellipse = new Ellipse2D.Double(100.0d, 100.0d, 100.0d, 100.0d);
        g2.fill(ellipse);
        g2.setTransform(orig);
    public void mousePressed(MouseEvent e) {
        if (SwingUtilities.isLeftMouseButton(e)){
            scale = scale + scaleInc;
        } else if (SwingUtilities.isRightMouseButton(e)){
            scale = scale - scaleInc;
            if(scale < MIN_SCALE)
                scale = MIN_SCALE;
        loc = e.getPoint();
        repaint();
    public void mouseClicked(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mouseDragged(MouseEvent e){}
    public void mouseMoved(MouseEvent e){}
    public static void main(String[] args) {
        ZoomTest2 internalPanel = new ZoomTest2();
        internalPanel.setBorder(BorderFactory.createTitledBorder("Zoom test"));
        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLayout(new FlowLayout(FlowLayout.CENTER));
        window.add(internalPanel);
        window.pack();
        window.setVisible(true);
}

Similar Messages

  • I am moving from PC to Mac.  My PC has two internal drives and I have a 3Tb external.  What is best way to move the data from the internal drives to Mac and the best way to make the external drive read write without losing data

    I am moving from PC to Mac.  My PC has two internal drives and I have a 3Tb external.  What is best way to move the data from the internal drives to Mac and the best way to make the external drive read write without losing data

    Paragon even has non-destriuctive conversion utility if you do want to change drive.
    Hard to imagine using 3TB that isn't NTFS. Mac uses GPT for default partition type as well as HFS+
    www.paragon-software.com
    Some general Apple Help www.apple.com/support/
    Also,
    Mac OS X Help
    http://www.apple.com/support/macbasics/
    Isolating Issues in Mac OS
    http://support.apple.com/kb/TS1388
    https://www.apple.com/support/osx/
    https://www.apple.com/support/quickassist/
    http://www.apple.com/support/mac101/help/
    http://www.apple.com/support/mac101/tour/
    Get Help with your Product
    http://docs.info.apple.com/article.html?artnum=304725
    Apple Mac App Store
    https://discussions.apple.com/community/mac_app_store/using_mac_apple_store
    How to Buy Mac OS X Mountain Lion/Lion
    http://www.apple.com/osx/how-to-upgrade/
    TimeMachine 101
    https://support.apple.com/kb/HT1427
    http://www.apple.com/support/timemachine
    Mac OS X Community
    https://discussions.apple.com/community/mac_os

  • What is the best way to make a DVD from iMovie

    What is the best way to make a DVD from iMovie?
    I am using iMovie 06 (Naturally) with iDVD 08. I have always used;
    iMovie 06, File > Share to iDVD 08. And got pretty good results.
    Some say the best way is to quit iMovie 06, open iDVD and import the movie from the Media button.
    I have tried both methods in the results look the same. I'm interested in getting the very best quality possible.

    You likely have one of the most expensive media converter boxes on the market today.
    But does it work well with most macs? (my guess is that it does). But more specifically can it "handshake" with an intel based mac? I personally haven't tried it.
    But you may want to read this for yourself if you haven't already:
    http://discussions.apple.com/thread.jspa?threadID=1179361&tstart=2362
    Assuming it works then the best format is .dv which this unit will support apparently.

  • What is the best way to make a list of addresses for envelopes or labels?  Address book, numbers or pages?

    What is the best way to make a list of addresses for envelopes and labels?  Address book, Pages or Numbers?

    I liek your idea of having multiple images in a grid. I think
    that would be the best bet as you mentioned. Having one big picture
    would be hard to distinguish the sub-areas with mouse coordinates.
    I think checking the coordinates for the mouse would be very
    tedious because I would have to check for the left boundary, the
    right, top, and bottom for each sub-area!
    What do you mean by using button components and reskinning.
    Is this simply using buttons and changing the way they look? I'm
    just trying to save time and memory, because if I had a 10 by 10
    grid, thats a hundred buttons. Wouldn't that slow down the machine
    alot? And for that matter wouldn't having a grid of 10 by 10 images
    also by the same deal?
    Thanks for the input, I'm just trying to find the most
    efficient way to do it.

  • What is the best way to make a clickable grid

    What would be the best way to make a clickable area that can
    differentiate between discrete parts of the area when clicked on.
    In other words, instead a having multiple buttons in a row that the
    user can click on, is there a way to have an area that has lines to
    distinguish the different areas(buttons) but that acts as though
    there were multiple consecutive buttons?
    For example, if I wanted to graphically simulate the buttons
    on a phone but without using buttons. Instead use some kind of grid
    or area that is divided into multiple sub areas that can
    distinguish the discrete positions (each button on the phone, or
    sub-area).
    Thank you,
    Salchichasa

    I liek your idea of having multiple images in a grid. I think
    that would be the best bet as you mentioned. Having one big picture
    would be hard to distinguish the sub-areas with mouse coordinates.
    I think checking the coordinates for the mouse would be very
    tedious because I would have to check for the left boundary, the
    right, top, and bottom for each sub-area!
    What do you mean by using button components and reskinning.
    Is this simply using buttons and changing the way they look? I'm
    just trying to save time and memory, because if I had a 10 by 10
    grid, thats a hundred buttons. Wouldn't that slow down the machine
    alot? And for that matter wouldn't having a grid of 10 by 10 images
    also by the same deal?
    Thanks for the input, I'm just trying to find the most
    efficient way to do it.

  • What is the best way to make a 30 minute video lecture taken with my iPad available to my university class? Email and USB transfer do not seem to have the capacity. Thanks!

    What is the best way to make a 30 minute video lecture taken with my iPad available to my university class? Email and USB transfer to the PC in the classroom do not seem to work because of the file size. Thanks! Quincy

    How to Transfer Photos from an iPad to a Computer
    http://www.wikihow.com/Transfer-Photos-from-an-iPad-to-a-Computer
    Importing Personal Photos and videos from your iOS device to your computer.
    http://support.apple.com/kb/HT4083
     Cheers, Tom

  • What is the best way to make a program fit different monitor resoultions?

    In our lab all our test stations have 1280x1024 resoultion monitors. In the "other lab" all the test station monitors are 1440x900 resoultion.
    Now I am tasked with making my programs run on the test stations in the other lab. I have tried setting the options "maintain proportions of windows for different monitor resoultions" and "Scale all object on front panel as the windows resizes" and of course neither one of these options really does what I would expect it to do.
    What is the best way to make programs fit different monitor resoultions?

    J-M wrote:
    I resize the Front Panel when the program start to fit the monitor resolution.  After that, I use the "SBE_Determine If Screen Resized.vi" from TomBrass (http://forums.ni.com/t5/LabVIEW/Resizing-controls-on-a-tab-control-within-a-pane/td-p/1520244 ).  This vi is very useful if you don't want to monopolize the CPU with the "Panel Resize" event.
    I don't like this function for a couple reasons.  First for the example you don't need any custom code to handle the window resizing, just use a couple splitters.  Even if you did need to handle the resize, you only resize after the mouse is up after the resize which is not how normal Windows programs work they resize as the mouse moves.  So I modified the VI to resize objects as you resize the window.  Then because doing this can generate 100 events very quickly, I use a boolean in a shift register to make sure that we only handle the resize event if there is no new resize events after 0ms.  This essentially makes a lossy queue and handles the last resize event.
    Unofficial Forum Rules and Guidelines - Hooovahh - LabVIEW Overlord
    If 10 out of 10 experts in any field say something is bad, you should probably take their opinion seriously.
    Attachments:
    Resizable_Graph.vi ‏22 KB

  • What is the best way to make drawings an notes during class (on my iPad), which I can add to my (digital) handout later on?!

    What is the best way to make drawings an notes during class (on my iPad), which I can add to my (digital) handout later on?!

    Hello BDAqua, thanx for the suggestions. Before I saw this reply I tried to first quit the finder and then to relaunch the Finder but that resulted was a blank gray screen.
    In the end I ended up having to power down the iMac.
    Fortunately the RAID array that was "active" seems to be fine and also has a firewire 800 connection so I can use it_ just not with thunderbolt until this issue is solved.
    I'm going to check in the Applications>Utilities>system log to see if any clues are evident_ thank you for the suggestion.
    PS: Nothing of note was obvious as a root cause in the Activity Monitor though.
    hmmm....I was told that the Helios and seritek card were compatable and that the Helios didn't require any drivers..it will be a drag if there isn't an easy fix for this since this new PCIe card from seritek is the first to offer port multiplier compatibility for eSATA to thunderbolt...since they are both new I'm hoping that an OS upgrade will be the fix (presently7.2)...we shall see.

  • What is the best way to make  certain cost centers as REQUIRING an internal

    Hello,
    What is the best way to make  certain cost centers as REQUIRING an internal order (when entering invoices in the accounts payable module u2013 transaction code FB60). At the present, if a cost center requires an internal order, and the employee who is  is entering the invoice in FB60 forgets to include the Internal Order, the invoice is incorrectly costed.
    Regards,
    Saeed

    Hai !!!
    The below method can solve your problem
    1.Create Internal order for each cost center from transaction code KO01 - Create and  enter the cost center under Requesting  CCtr
    2. Enter internal order or costcenter / while user post the transaction
        Example Fb60
    Regards
    shamul heq

  • The Best way to make an Apple password protected PDF file?

    1. Any idea? Because I need to send Password protected PDF files to my clients and family too, how strong is it?
    2. There are two ways to make a protected PDF, one is "Print" to PDF, the other is "Save As" to PDF. What's the difference between them? I found the two different means result two different file size, Why is that?
    3. Which one is the best way to make a Password protected PDF in Mac?

    I got these results by Ubuntu 10.04 LTS freeware named "PDF cracker", but I don't know what these info. mean.
    PDF version 1.4
    Security Handler: Standard
    V: 2
    R: 3
    P: -4
    Length: 128
    Encrypted Metadata: True
    FileID: 04513685582ec58cb4f0fec807d21269
    U: a0d296dbc7e7bf3bd7df37877a8f15e600000000000000000000000000000000
    O: 4ab5ab7c0b79369c4f24a5f7caeeb6fd14fe46ae1563ffcb250ee01a3e678209
    The cracking is still under way, 15 mins past, it still hasn't cracked it yet.
    The password length is 7 characters.
    What is Meta data? V? R? P? What does that mean?
    What Length is it talk about?
    Check this out --> http://sourceforge.net/dbimage.php?id=79230

  • The Best Way to make your iPad battery last the longest!

    After checking many sources and also discussions here -- this is one article that pretty much sums up the best way to make your iPad battery last the longest!
    It basically comes down to JUST ONE THING (mainly) -- and that is simply REDUCING YOUR CHARGE CYCLE COUNT! And how do you do that? Well, very simply KEEP IT PLUGGED IN as much as possible. And then, doing what Apple says by doing just one full discharge - once a month.
    There are about 1000 charge cycles available for the iPad, at which point you should have 80% of the battery life left. SO ... Anything you do to slow down getting to that 1000 charge cycles, makes your iPad battery last longer. Keeping it plugged in "all the time" (or, as much as possible - since it is a portable object) slows down the process of getting to that "lessening of battery capacity". It's simply all about "charge cycles" - which then translates into "reduced battery capacity".
    Here's an article to pay close attention to:
    Best Practices for iPad Battery Charging
    http://www.ilounge.com/index.php/articles/comments/best-practices-for-ipad-batte ry-charging/

    Here's another site that is usually posted here that you would be interested in: http://batteryuniversity.com

  • What is the best way to make PSD into HTML for emails

    What is the best way to make PSDs into HTML for emails? Will the new feature in Dreamweaver work for emails as well? I am using Cheetah mail, but I need to be able to turn PSDs into HTML so I can use it in Cheetah mail.  I have a general idea of how to do this, but I'm stumped about where to begin.

    Use PShop for images only.  Use DW to create your tables and inline CSS styles.
    Many e-mail clients do not show images for security reasons.  So graphics heavy e-mails are not an optimal way to communicate with your mailing list.
    See Alt-Web Articles, HTML E-mails and Newsletters
    Nancy O.

  • What is the best way to make skin uniform (not necessarily blurring it!)

    Hi,
    I have some photographs where the skin of the model's leg is not of uniform brighteness. Without blurring it, I have tried the clone stamp but it is very difficult to not introduce further variations in brightness.
    What is the best way to make skin uniform in brightness (actually, the same color!)?
    Thanks,
    Juan Dent

    I know EXACTLY what you mean.  I was doing something exactly on those lines just yesterday.
    It's not trivial, but it's doable.
    For hard "spots", you can try the Spot Healing Brush first.
    But here's a neat trick I sometimes use that can nicely increase the overall smoothness:
    1.  Select just the skin area.
    2.  Contract the selection a bit and feather the edge, just to make sure you don't mess up the edges.
    3.  Filter - Noise - Median, and adjust the radius to be fairly large.  Watch the image to see the smoothness level.
    4.  Edit - Fade and knock back the effect, so that it's not perfect, but makes a subtle improvement.
    Then, for gentle darkening lightening, try the Burn and Dodge Tools, set to a low Exposure level (and possibly with Airbrush Mode on).  Work gently.
    Cloning with low opacity can sometime help as well.
    -Noel

  • What's the best way to make a bootable, incremental backup of Boot Camp?

    I'm curious as to what's the best way to make a bootable and incremental backup of Boot Camp, similar to Time Machine? I'd essentially like it to replace System Restore as well, because that's currently not working for me (System Restore backups get deleted every time I restart).

    System Restore gets backed up to what and where?
    You need system image one way or another, and you want data and file backup.
    Windows 8 takes File History feature is similar to TimeMachine but not for system.
    Take a look at Paragon Hard Disk Manager 12 Suite, has Boot Camp support.

  • Whats the best way to make a slideshow DVD

    Hi, Finally I got my iMac the other day and have been playing around and trying to get the best out of it and was hoping to get some help from here. I have been playing with ilife on a friends mac for a while but never had a go in anger and now need some proper answers. Its quite simple. I create photo dvd slideshows and need to find the best way to do it. As far as I can tell there are a few ways. I can use imovie to get the running order - add the Ken Burns effects (that I DO need) - add music - add transitions and "share" to a .mov file and drag this into iDVD to put a menu on. Ok - this works but I get some MPEG artifacts (I know this is to be expected - I have been doing this for years on a PC). I can drag photos into iDVD but as far as I can tell I cannot have Ken Burns so this is out. I can use iPhoto to make a .mov file and again import this into iDVD. Am I missing something here? iMovie08 seems great and the .mov file is good enough quality to re-render in iDVD without losing too much quality so I guess this is the way to go but is there no way to go without rendering the .mov file and then going into iDVD? I have also used iMovie06 before and it had better transitions between photos - have these been lost in iMovie08?? I have set the quality in iMovie08 to "Profesional" but there stil seems to be a bit of artifacting. Should I try Toast?
    Apologies for the long post but am really keen to get this sorted. I have posted before on here and got great responses but just want to get it right 100% before putting lots of effort in. I have next week off work to perfect the photos to DVD slideshow before I start to try to sell these things! many many thanks.Ben

    I am still using my old 3 chip Sony TRV900 capturing to mindv tape and then importing that footage via FW into iM6 => iDVd'08. Frankly my own iDvd's look crisp and clean well over 90% of the time (But then again most my presentations are often under 60 mins duration in order to keep compression down to a minimum). They are well lit or often outdoors. And I avoid videotaping fast moving objects or panning the camera too quickly. I notice a significant quality shift (toward that of VHS quality ) if I shoot over 90-120 mins, & I often regret doing so since it requires the i-apps to work much harder and at times with marginal results.
    The trick I think is to keep it short and sweet and to avoid higher compression rates.
    That or move the video footage over to FCP => Compressor => DVDSP. But from experience I have found that anything over 90 mins. (regardless of the app I use) tends to look much like VHS quality..... disappointing to say the least in that jaggies begin to set in, and even tho I am using a 3 chip camera; color separation suffers greatly on a 2 hour standard DVD-R.
    I do not yet shoot HD nor do I own a Blueray Burner which is the very next step many of us will require of apple if and when we are to burn HD to disc. At the moment it's simply not supported on most macs. To date Blueray has not been widely incorporated into most macs either thru i-apps nor thru apple's pro apps from what I have observed.

Maybe you are looking for