Rotate both image and a panel drawan on it

Hi all,
I need to perform this task:
1. Display an image on the screen
2. Position a Jpanel on the image
3. Rotate the Image with the help of mouse
4. JPanel should be rotated accordingly.
I need help regarding the classes to use to perform it.
Thanks in advance,

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
public class SpinningContext extends JPanel {
    BufferedImage image;
    double theta = 0;
    SpinningContext(BufferedImage image) {
        this.image = image;
        setLayout(null);
        JPanel panel = new JPanel();
        panel.setBackground(Color.red);
        Dimension d = getPreferredSize();
        int w = 40;
        int h = 50;
        int x = (d.width - w)/2;
        int y = (d.height - h)/2;
        panel.setBounds(x, y, w, h);
        add(panel);
    protected void paintComponent(Graphics g) {
        int w = getWidth();
        int h = getHeight();
        int x = (w - image.getWidth())/2;
        int y = (h - image.getHeight())/2;
        g.drawImage(image, x, y, this);
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        Rectangle r = getBounds();
        g2.setColor(getBackground());
        g2.fill(r);
        double x = r.getCenterX();
        double y = r.getCenterY();
        AffineTransform at = AffineTransform.getRotateInstance(theta, x, y);
        g2.setTransform(at);
        super.paint(g);
    public Dimension getPreferredSize() {
        return new Dimension(400,400);
    public void setTheta(double theta) {
        this.theta = theta;
        repaint();
    public static void main(String[] args) throws IOException {
        String path = "images/geek/geek----t.gif";
        BufferedImage image = ImageIO.read(new File(path));
        SpinningContext test = new SpinningContext(image);
        ContextSpinner spinner = new ContextSpinner(test);
        test.addMouseListener(spinner);
        test.addMouseMotionListener(spinner);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(test);
        f.pack();
        f.setLocation(200,200);
        f.setVisible(true);
class ContextSpinner extends MouseInputAdapter {
     SpinningContext component;
     Point2D.Double center = new Point2D.Double();
     boolean dragging = false;
     double theta;
    ContextSpinner(SpinningContext sc) {
        component = sc;
    public void mousePressed(MouseEvent e) {
        Rectangle r = component.getBounds();
        center.setLocation(r.getCenterX(), r.getCenterY());
        theta = getTheta(e.getPoint());
        dragging = true;
    public void mouseReleased(MouseEvent e) {
        dragging = false;
    public void mouseDragged(MouseEvent e) {
        if(dragging)
            component.setTheta(getTheta(e.getPoint())-theta);
    private double getTheta(Point p) {
        double dy = p.y - center.y;
        double dx = p.x - center.x;
        return Math.atan2(dy, dx);
}Image from:
http://java.sun.com/docs/books/tutorial/uiswing/examples/components/index.html

Similar Messages

  • Have a MacBook Pro running Lion and an IMac running Snow Leopard. Want to Back up both images and restore on opposite machine. Essentially swapping images between hard drives. Is this possible and any "gotcha's" to look for? Thanks

    Have a MacBook Pro running Lion (10.7.9) and an IMac running Snow Leopard (10.6.8). Want to Back up both images and restore on opposite machines. Essentially swapping images between hard drives. Is this possible and any "gotcha's" to look for? Thanks

    If the MBP came with Lion, it most likely won't boot with SL. Easiest thing to do is create a bootable backup/clone of each to an ext HD, partitioned to hold each on a separate volume, ensure that the original machines can boot with their respective clones, and finally, try booting the other machine with the other clone. Images are useless since you can't boot with them to test them out.

  • Rotating an image and getting back the image...

    Hi,
    I have a small problem using images...
    1. I have an existing image...
    2. I need to rotate the image by a certain angle(say 60 degree)....
    3. Return the rotated image back to the calling routine...
    My problem is that I can rotate the image using the AffineTransform, and draw the image immediately... but I cannot return the rotated image... can anyone help me out on this??????

    No sorry that didn't fix it. I forgot to mention that I already have a method in ImagePanel called clearImage()
         * Clear the image on this panel.
        public void clearImage()
            if(panelImage != null) {
                Graphics imageGraphics = panelImage.getGraphics();
                imageGraphics.setColor(Color.LIGHT_GRAY);
                imageGraphics.fillRect(0, 0, width, height);
                repaint();
        }But if I clear the panel and then try to apply the function nothing happens. The LIGHT_GRAY background remains.
    This is how I apply a function in the class[b] ImageViewer
         * Apply a given function to the current image
        private void applyFunction(Function function)
             if(currentImage != null) {     
                  if(function.getName().equals("Zoom In")) {
                       Zoom.ZOOMIN_RATE = 1.5;
                       function.apply(currentImage);
                  else if(function.getName().equals("Zoom Out")) {
                       Zoom.ZOOMIN_RATE = 0.5;
                       function.apply(currentImage);
                  else {          
                       imagePanel.clearImage();
                       function.apply(currentImage);    //A function is applied                   
                  frame.repaint();              
                  showStatus("Applied: " + function.getName());
             else {
                  showStatus("No image loaded.");
        }

  • In Preview I rotate an image and save it, but when not when uploaded?

    What's the screwey deal with Preview?
    I open the image, rotate it, save it...but when I upload it to the internet, it remains in its original position.
    Whats going on there?
    Thanks for your help.
    -ankitae

    I can confirm this, but don't know why.
    Jpeg's rotated with Preview don't display rotated when displayed in web browsers.
    Jpeg's rotated with Preview do display up rotated when displayed with GraphicConverter
    Jpeg's rotated with Graphic Converter show up rotated when displayed in web browsers.
    For the short, quick fix, I'd suggest trying Graphic Converter... It usuall comes as part of the software package on your Mac.
    Someone from the graphics world will be able to provide a better answer as to why, but I have no idea.

  • Appending data(Image and Text) to a file written with RTFWriter2.

    I have file witten using RTFWriter2 which contains image and text.I nedd to modify the contents of that file at runtime through browsing and selecting the JFileChooser and append the data to existing selected file.
    I write inot the file for the first time using FileOutputStream("filename",ture)
    where true stands for appending data to current file,if does noes have any/not.
    But this does not work when i write the file using RTFWriter2,and i have to use this RTFWriter2 b'coz writing an image to a file is not done by any other way.
    If there is any do let me know and if not then what is the solution to this problem of appending data to existing file written by RTFWriter2.
    Your repkeis will be appreciated.Thank You.

    Mubin_Ahmed wrote:
    Hi,
    I want to write an application which can be used to read a file that contains both images and text.
    It must separate the images and text and write them in separate files..
    Can anyone help me with this please...
    My email id is [email protected]
    Thanks in advance...This forum is to use as a resource for your questions, not a place to enlist someone to program for you. If you have specific questions on what to do, not: "I've not a clue, so explain the wold to me." But specific questions on how to get your code to work or points about Java, then people from all over the world will be happy to help you in the context of the forum, and not through your private e-mail. E-mail defeats the basic purpose of having public forums for learning and exchange of information.

  • Horizontal RSS feed- is it possible to create an RSS feed (showing both pictures and text), that scrolls from left to right rather than top to bottom?

    I am trying to create an RSS feed that will scroll from left to right rather than top to bottom as is standard in iWeb.  Ideally, I would like to show both images and text. I am actually using iWeb '09.  I am not opposed to writing html code if necessary.
    Thank you for your help!

    Probleme solved without having to change anything in the flash.
    The solution was to add a small part in the CSS in HTML
    html {
    overflow-x: hidden;
    overflow-y: auto;
    Solve probleme. All browser. VERY usefull to know !

  • Problems to rotate rectangular images

    Hello,
    I wrote code to rotate BMP images, and it works very good with square images. But it doesn't work with rectangular ones. When I try to rotate them, I obtain an images with all pixels in a wrong position, so that it is impossible to understand the content... WHY ??
    thank you
                        //BufferedImage toStore
                        BufferedImage toStore = new BufferedImage(Width,Height,BufferedImage.TYPE_INT_RGB );
                        Graphics2D g2d =toStore.createGraphics();
                        //double centerX = (Height - Width)/2.0;
                       //double centerY = (Width - Height)/2.0;
                        double centerX = Width/2.0;
                       double centerY = Height/2.0;
                       AffineTransform rotationTransform = new AffineTransform();
                       rotationTransform.rotate(Math.toRadians(Degrees), Width/2.0, Height/2.0);
                       // draw the image using the AffineTransform
                        g2d.drawImage(img, rotationTransform, null);

    ok sorry. I made a stupid mistake some lines after.
    thank you anyway!Ah yes. It's always where you least expect it.

  • When I rotate my video clip so that is isn't viewed sideways, it has black bars on both sides and some of picture is missing. Can I rotate the image so it plays rightside up without the black bars? The image was taken by an iPhone. I am viewing it on PC

    When I rotate my video clip so that is isn't viewed sideways, it has black bars on both sides and some of picture is missing. Can I rotate the image so it plays rightside up without the black bars? The image was taken by an iPhone. I am viewing it on PC

    Just to recap, this is a collection of ports I have collected over time for people who needed this information when setting up the HP ePrint app so that they could view their email from within the app.  I am certain other applications also need this information.  Although lengthy, I could not find a more comprehensive place to retrieve this information.  Feel free to post additional information, faulty information, or other related topics below as this is simply a collection of data and it would be practically impossible to test all of them. Thank you!
    Don't forgot to say thanks by giving "Kudos" if I helped solve your problem.
    When a solution is found please mark the post that solves your issue.
    Every problem has a solution!

  • I have a Flash Sample to rotate images and text but I not find a way to display special characters

    Hello everyone.
    I bought a very nice Flash application that rotate images, and text of any color and size. It use an XML input file.
    I've posted here, a complete copy, so any of you can download, view and use it freely.
    I would appreciate if any of you know how to do, so that the text displayed, including the characters I use in my language (Spanish), such as á, é, í, ó, ú, ñ, and other special characters.
    In fact, I could not find a way to do it, because I'm not expert Flash, and less in ActionScript.
    If any of you would help me on that, I thank you implement the appropriate adjustments and compressed into a. zip file, and let me know where to download it, or if you prefer you can send it to my email: [email protected]
    After all compressed in .zip format is a very small file: 430K.
    Click here to download the complete sample.
    Thanks.
    =====================================
    Translated using http://translate.google.es
    =====================================

    Hello Rinus,
    If I understood your last post correctly, then problem 2 is resolved, right?
    Regarding problem 3:
    I'm not asking you to share exact VIs.
    I just want to see a very simple VI that explains the concept of what you're trying to do, what should happen (this can be in words that refer to the front panel elements) and what you've tried.
    The terminology you're using isn't clear to me without an extra explanation.
    This could even be only a Front Panel with a few buttons on where you just describe what should happen with specific controls/indicators.
    Based on the first post it is not clear to me what you mean with:
    - A "button element":
      Are you talking about a control, an indicator, a cluster that contains multiple control?
    - The structure:
      Is this an event structure, case structure, for loop, ...?
    Is it seems like you want to programmatically control Front Panel objects, which on itself is no problem at all independent of how many objects you want to control.
    Please share with me simple example of what goes wrong and explain which things should happen on that specific Front Panel.
    This will allow me to help you and also allow me to guide you along the right path.
    Kind Regards,
    Thierry C - Applications Engineering Specialist Northern European Region - National Instruments
    CLD, CTA
    If someone helped you, let them know. Mark as solved and/or give a kudo.

  • Image rotation in Photoshop and Premiere Elements 9

    I have used Photoshop Elements in the past to create slideshows, then edited them with Premiere Elements.  Since I installed version 9, I now have a problem with rotated images.  The images I rotate in Photoshop do not show up as rotated in Premiere.  I went to preferences in Photoshop and unchecked the box for JPEG orientation, which rotated the image on my hard drive.  Now, the image appears rotated in Premiere but it is distorted.  Is there a solution for displaying the rotated images correctly in both applications?

      Normally if you click Output à Edit With Premier Elements from the slideshow editor your project is normally sent to the PRE timeline with the same orientation.
    In PRE you can right click on the slideshow clip and choose break apart. If you then click in the main window a bounding box will appear around your frame. You can then hover your cursor around the corner until the double arrow appears and rotate in any direction.
     

  • How do I find images in LR 2.4 (imported from CS4 Bridge) that have color labels already assigned In CS4 Bridge? I have set both Bridge and LR color labels text to match (eg Green for green, etc).

    How do you find images in LR 2.4 that have been imported from CS4 Bridge and have been assigned a color label in Bridge?  I have set both LR 2.4 and my CS4 Bridge to match the text for each color to be the same (eg. Green for green, etc), and the filter search in LR 2.4 shows that a label has been assigned, but I am unable to identify and locate the specific images in LR 2.4 that have had a color label assigned from CS4 Bridge.  I have tried to search via attribute, metadata, text, etc...Is it necessary to re-assign color labels all over again, image by image, in LR 2.4, or is there a way to automatically have the color labels assigned in CS4 Bridge be assigned and searchable to the images after they have been imported into the LR 2.4 catalogue from the Bridge program?

    JohnM.
    I closed both programs and re-imported photos and re-tried the action of having LR  read the XMP metadata from the CS4 files, and it seems to work now just fine...don't know why now and not before, but thanks much. Is there a way to have LR do this automatically upon import of images from CS4?  I tried to do this with an import metadata preset, but no luck.  It seems as if I can only do this once the images have already been imported into LR, and then to have to have LR read the metadata from the CS4 Bridge files.  thanks gain.

  • How to get background image to fill the browser and remain fixed in both IE and Firefox?

    Basically what it says in the title. I've come very close in achieving this but something just doesn't tie up in the html and css code...
    First of all, I'm using IE8 and the latest version of Firefox to test this.
    I used 2 sources of information for getting this done: 1) http://css-tricks.com/perfect-full-page-background-image/ and 2) http://stackoverflow.com/questions/8958697/css3-background-size-cover-doesnt-make-image-co ver-vertically
    In Case 1 the example on the page called CSS-Only Technique #1 gives code that works almost perfectly for me, except that obviously I need a background image, however the CSS provided there is clearly just for an image dropped in the body of a page with no regard for other content that may already be there. The html code that I put on the page is simply <img class="bg" src="../images/background_image.jpg">
    Obviously I used the CSS code provided in the example, minus the last bit which is "@media screen" etc etc, which seems irrelevant to me. Obviously substituting values to suit the image on my page.
    So what happened is that it almost worked as intended in both the browsers (which means the image filled both browsers width-wise as intended and also remained fixed when I zoomed in or out in each case) except that the image went over the top of the current content that I had there already precisely because it's not a background in this "technique". (A curious side-note is that the image didn't push down the content, as I'd have expected in normal circumstances, but went right over the top of it so it hid it (like z-index).
    One thing that does bother me about this "technique" is that if you click on View Demo just below the code provided you will see on the working example page (forest background) the image clearly works as a background and the content sits happily on top! So I don't know whether the person providing the example was trying to mislead people or what! Or he got lazy and showed a different page that didn't use the exact code he provided. No matter.
    In any case this leaves me with the job only half finished, as I still need a background image that works like the 'normal image' code provided.
    On to Case 2 and on this page the first example provided gives the CSS for the background image - namely the code within html {...} part and also shows the same 'normal image' code as given in Case 1. In this case however, although the person provided a suggestion, the css and html doesn't really tie up properly plus some of the css and html seems a bit redundant. So this time when I used the 'html portion' of the CSS code (i.e. just the bit that was most relevant) I got two different behaviours in each browser and neither of which was quite what I'm looking for. In IE8 initially the page looks fine (background fills the page and content is on top) however when I zoom in or out the background also zooms in or out accordingly so is NOT fixed. In Firefox the background image DOES stay fixed, however because the image originally is not the whole height of the browser I'm guessing the code stretches it downwards (while keeping proportions - so the image essentially enlarges) to fill all of it. The quick way to get around it is to probably add some white space to the bottom of the image just to give it enough height that it doesn't stretch/resize automatically. But it would be nice to find out anyway how to get around this in the code. Overall I would say that the result in Firefox comes closest to the desired solution but of course it doesn't help matters with IE8.
    Apologies for the lengthy description but that should at least provide plenty info for anybody that might have a possible solution for me. Essentially what would be great is if somebody could advise me how to take the code from Case 1 and apply it to a 'background' piece of coding like the type that's contained within html {...} in Case 2. Like I said, it's so nearly there but I just can't make it work atm after trying to combine the various bits of code this way and that... Alternatively, if somebody has another html-css version that works nicely for achieving this then please by all means let me know! Thanks v much in advance!

    This works in modern CSS3 supporting browsers.  But not pre-IE9.
    http://alt-web.com/TEST/Resizable-BG.shtml
    Nancy O.

  • Best-practice for use of object styles to manage image text wrap issues when aiming at both print and EPUB output?

    I have a work-flow question about object styles, text-wrap, and preparing a long document with lots of images for dual print/EPUB output in InDesign CC 2014.
    I am sort of experienced with InDesign but new to EPUB export. I have hundreds of pages and hundreds of images so I'd like to make my EPUB learning curve, in particular, less painful.
    Let me talk you through what I'm planning and you tell me if it's stupid.
    It's kind of a storybook-look I'm going for. Single column of text (6" by 9" page) with lots of small-to-medium images on the page (one or two images per page), and the text flowing around, sometimes right, sometimes left. Sometimes around the bounding box, sometimes following the edges of the images. So in each case I'm looking to tweak image size and placement and wrap settings so that the image is as close to the relevant text as possible and the layout isn't all wonky. Lovely print page the goal. Lots of fussy trade-offs and deciding what looks best. Inevitably, this will entail local overrides of paragraph styles. So what I want to do, I guess, is get the images as closely placed as possible, before I do any of that overriding. Then I divide my production line.
    1) I set aside the uniformly-styled doc for later EPUB export. (This is wise, right? Start for EPUB export with a doc with pristine styles?)
    2) With the EPUB-bound version set aside, I finish preparing the print side, making all my little tweaks. So many pages, so many images. So many little nudges. If I go back and nudge something at the beginning everything shifts a little. It's broken up into lots of separate stories, but still ... there is no way to make this non-tedious. But what is best practice? I'm basically just doing it by hand, eyeballing it and dropping an inline anchor to some close bit of text in case of some storm, i.e. if there's a major text change my image will still be almost where it belongs. Try to get the early bits right so that I don't have to go back and change them and then mess up stuff later. Object styles don't really help me with that. Do they? I haven't found a good use for them at this stage (Obviously if I had to draw a pink line around each image, or whatever, I'd use object styles for that.)
    Now let me shift back to EPUB. Clearly I need object styles to prepare for export. I'm planning to make a left float style and a right float style and a couple of others for other cases. And I'm basically going to go through the whole doc selecting each image and styling it in whatever way seems likeliest. At this point I will change the inline anchors to above line or custom, since I'm told EPUB doesn't like the inline ones.
    I guess maybe it comes down to this. I realize I have to use object styles for images for EPUB, but for print, manual placement - to make it look just right - and an inline anchor seems best? I sort of feel like if I'm going to bother to use object styles for EPUB I should also use them for print, but maybe that's just not necessary? It feels inefficient to make so many inline anchors and then trade them for a custom thing just for EPUB. But two different outputs means two different workflows. Sometimes you just have to do it twice.
    Does this make sense? What am I missing, before I waste dozens of hours doing it wrong?

    I've moved your question to the InDesign EPUB forum for best results.

  • I use to be able to rotate my iPhone and change the view of an image, Web page, email, and so on, from portrait to landscape, but after update, I cannot. I can only view in portrait mode. Anybody know what's up with that?

    I use to be able to rotate my iPhone and change the view of an image, Web page, email, and so on, from portrait to landscape, but after update, I cannot. I can only view in portrait mode. Anybody know what’s up with that?

    You need to do the basic troubleshooting steps described in the User Guide, Appendix B.
    Restart phone
    Reset phone
    Restore in iTunes using a backup
    Restore in iTunes as new, without using a backup
    If restoring as new doesn't help, there is a hardware failure in the phone that needs evaluation by Apple.

  • Problem In moving 1 image from 1 panel to next and maintain size of original image?

    Why is it when i drag one image from the bottom panel over to another picture(solid color) i will only get 50% of the image and not the full image. Same thing when i copy and paste that image over the gray solid colored image also i will get only 50% of the image.  The original image of the cat(full view) is about 24.79%  and picture is 11.733 x 15.644 in size.  the other image (solid color) is at 43.63%  or 6.667 x 8.889". size is in inches. Do i have to resize the images and if so how as i am a stupie in this matter. The images are aligned side by side on the main panel or display.I am trying to place the cat over the gray background image  and with a layer mask delete the present baackground of the cat to uncover the gray of the bottom layer.  Thanks!!

    Probably the resolution of each image has a different value. You can check this in Image>resize>image size. The resolution is expressed in px/in.
    If you are attempting to place the cat on a plain gray background, try this:
    Set your foreground color chip  (lower left) to the shade of gray desired
    Open the picture with the cat
    Using one of the selection tools (e.g. Selection brush, lasso), select the cat
    Place the cat on a separate layer (Layer>new>layer via copy)
    Place a blank layer between the background layer and the cat layer
    Fill the blank layer with gray ( Edit>fill layer>foreground color)
    Use the move tool to position the cat, and resize, if necessary, with the corner handles of the bounding box.

Maybe you are looking for

  • BT Infinity Connection Problems

    Hi, I recently got BT Infinity 2 at the start of the July after having enough of Virgin Media's awful service. When BT Infinity was first installed, the BT engineer said to me that I should be recieving around 60 download and about 20 upload due to h

  • How to duplicate screens?

    Is there any way to duplicate Screen1 without copy-pasting? I'd like to make a standard screen for my game app using Siena and I need like 100 levels of just the same one. 

  • Add Document ID to Invoices_all Table

    Hello, I would like to ask if there's a way i can add the document ID of attached documents as an extra attribute field to the Invoices_All table while creating invoices through quick invoices. Thanks in anticipation.

  • The real problem with Mail alerts in 10.5?

    The one change I have noticed between Mail in 10.4 and Mail in 10.5 is that the New Mail Alert sound now plays through the wrong device. In System Preferences you can set two separate devices (and volumes levels) for Alert Sounds and other sounds. Th

  • Debug technique to locate VI which is "hanging"/waiting. Pause button - is not working.

    During development I now and then experience that the top-vi simply "hangs". The debug Pause button does not break into the program - it turns red but nothing happens. I can stop with "Abort button", but then I can't see which vi was stuck in a waiti