[Beginner] Moving a simple Shape

Hi all !
I need to write a simple application which draws basic shapes and let the user drag this shapes.
I have found a sample code which does this with gif images rendered inside JLabels and adapted to use shapes (in this case a Ellipse2D) but nothing is drawn on the screen.
Why ?
Can anybody give me a help to fix it ?
Thanks
Francesco
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
public class Main implements MouseMotionListener {
     JFrame frame;
     JLabel img;
     private final Graphics2D offscreen;
     public Main() {
          frame = new JFrame("test");
          frame.getContentPane().setLayout(null);
          frame.setBounds(0, 0, 500, 400);
          BufferedImage offscreenImage = new BufferedImage(200, 200,
                    BufferedImage.TYPE_INT_RGB);
          offscreen = offscreenImage.createGraphics();
          offscreen.setColor(Color.BLACK);
          offscreen.draw(new Ellipse2D.Double(10, 10, 120, 120));
          ImageIcon icon = new ImageIcon(offscreenImage);
          JLabel draw = new JLabel(icon);
          draw.addMouseMotionListener(this);
          frame.getContentPane().add(draw);
          frame.setVisible(true);
     public void mouseMoved(MouseEvent e) {
     public void mouseDragged(MouseEvent e) {
          img.setBounds(img.getX() + e.getX() - 10, img.getY() + e.getY() - 10,
                    36, 39);
     public static void main(String args[]) {
          new Main();
}

(1) When you use null layout you need to setBounds for each component, since there is no LayoutManager to take care of sizing and placement.
(2) A newly constructed BufferedImage is filled with black pixels and drawing in black wouldn't show anyhow.
Considering these two points, I've reworked your code... I renamed the reference variables as I find it inconvenient to have to remember that offscreen is in fact a Graphics2D object, and img is a JLabel. For future postings here, I strongly suggest that you name your variables after the class they represent... doing this will surely get you faster and better responses.import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main implements MouseMotionListener {
    JFrame frame;
    JLabel label;
    private final Graphics2D graphics2D;
    public Main () {
        frame = new JFrame ("test");
        frame.getContentPane ().setLayout (null);
        frame.setBounds (0, 0, 500, 400);
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        BufferedImage bufferedImage =
                new BufferedImage (200, 200, BufferedImage.TYPE_INT_RGB);
        graphics2D = bufferedImage.createGraphics ();
        graphics2D.setColor (Color.RED); // changed
        graphics2D.draw (new Ellipse2D.Double (50, 50, 100, 100));
        ImageIcon imageIcon = new ImageIcon (bufferedImage);
        label = new JLabel (imageIcon);
        label.setBounds (0, 0, 104, 104); // added
        label.addMouseMotionListener (this);
        frame.getContentPane ().add (label);
        frame.setVisible (true);
    public void mouseMoved (MouseEvent e) { }
    public void mouseDragged (MouseEvent e) {
        label.setBounds (label.getX () + e.getX () - 10,
                label.getY () + e.getY () - 10,
                label.getWidth (), label.getHeight ());
    public static void main (String args[]) {
        new Main ();
}You might want to use a MouseAdapter or add a MouseListener to capture the coordinates of mousePressed and use them as an offset for a more intuitive drag effect.
Cheers, Darryl
PS -- I'm not really into Graphics work, just trying to learn something new -- could you or somebody tell me why the Ellipse2D constructor doesn't seem to behave as per the documentation?
public Ellipse2D.Double(double x, double y, double w, double h)
Constructs and initializes an Ellipse2D from the specified coordinates.
Parameters:
x - the X coordinate of the upper-left corner of the framing rectangle
y - the Y coordinate of the upper-left corner of the framing rectangle
w - the width of the framing rectangle
h - the height of the framing rectangle
From this program, I found that x and y appear to be at the center, and not the upper-left corner, of the framing rectangle -- or is my understanding flawed?
db

Similar Messages

  • How to get at Colour drop down box for simple shape ?

    Hi,
    If I go new file, Insert Symbol, Movie Clip, then draw a
    circle and a line using those two tools, I am unable to get the
    colour drop down box to show so that I can select Alpha. I have
    managed to do this many times for an imported to library graphic
    from Freehand, one simply clicks on the graphics line after the
    graphic has been drag/dropped to stage, go properties and the
    Colour drop down list from where you select the word Alpha appears.
    I have tried a single click, a double click, a treble click,
    just cant see that dropdown box for simple shapes !
    Help
    Envirographics

    Hi,
    If I go new file, Insert Symbol, Movie Clip, then draw a
    circle and a line using those two tools, I am unable to get the
    colour drop down box to show so that I can select Alpha. I have
    managed to do this many times for an imported to library graphic
    from Freehand, one simply clicks on the graphics line after the
    graphic has been drag/dropped to stage, go properties and the
    Colour drop down list from where you select the word Alpha appears.
    I have tried a single click, a double click, a treble click,
    just cant see that dropdown box for simple shapes !
    Help
    Envirographics

  • Simple Shape Tween always causes Flash to freeze (CS3)

    Flash CS3 Professional is always freezing when I create a
    simple shape tween. The steps that I follow to produce this problem
    are as follows:
    Draw a line
    Bend the line into a curve.
    Set a second keyframe on the timeline. (doesn't matter how
    many frames between the two keyframes)
    Use the direct select tool to reposition the point at one end
    of the line.
    Set the tween to Shape between the two keyframes.
    Scrub the timeline.
    Flash freezes.
    According to the Windows XP Task Manager, the CPU is at 50%
    with most of that going to flash.
    Any ideas on how to get it working properly?
    I can do the tween successfully without issue using Flash 8,
    but CS3 freezes everytime. Our company won't let us upgrade to CS4
    at the moment.

    i can't duplicate that problem.
    if the problem occurs when you scrub the timeline, don't
    scrub it. test it in the test environment. you may be able get your
    tween working doing that (even though that doesn't solve the
    problem).

  • "Minus Front" a simple shape on top of a complex clipping mask

    I have a clipping path that is made up of:
    1. a complex assortment of vector shapes (a pattern) and
    2. a simple shape on top.
    My pattern appears to be inside the simple shape, because of the clipping mask.
    Now, I'd like to "punch-out" a shape in the middle of my clipping path, and have that punch-out be transparent. After creating my punch-out shape, I drag it to the same layer that has the clipping mask, select both (the clipping mask is below the punch-out shape), and slect "minus front" from the pathfinder window.
    It's not working.
    Any advice is much appreciated.

    bovine wrote:
    ... it's almost completly gone.
    It is hard to imagine how an almost completely gone object looks like in the Layer's panel
    See the little blue squares highlighted in the image, they indicate selected objects . This is called the Selection Column in the Layers panel. You can select any object with equal ease by clicking on the selection column - the red arrow points to the spot you can click to select that path.
    Also, another alternative method to make what you want is to make the punch out shape with 0 opacity, put it above and in the same group as the clipping path and in the Transparency panel click in the box in front of the Knockout Group until a checkmark appears.

  • Simple shape morphing in Keynote...?

    Hello,
    I am seeking help with what should be a simple task (I reckon), but which is turning out not to be...
    I use Keynote 9 for my teaching presentations. I need to show semi-transparent coloured regions – superimposed onto maps – that change through time, and I would like to make that change into a fluid animation: simple semi-transparent blobs that change shape. That's all! Simple, huh.
    Here are the problems...
    - The shapes are irregular (so Magic Move won't do it)
    - Keynote 9, so no Flash
    - I can get Adobe Illustrator to generate Flash animations and then I should be able to convert them with VideoMonkey into .mp4s... except that VideoMonkey utterly refuses to convert the .swf files generated by Illustrator...  No idea what's going on there... Tried everything I can think of, no go.
    - Downloaded a trial version of Mac SWF Video Converter, but this seems to make mp4s with black backgrounds...  I couldn't see any way to maintain the transparency (and of course Instant Alpha doesn't work on video files)
    - I can generate single animation frames in Adobe Illustrator then use Preview to combine them into animated GIFs, but Keynote will not import the result with a transparent background (yes, I can *make* them with a transparent background, but Keynote renders it solid white on import...)
    - I can convert the animated GIF to a QT movie (using GIF2MOV), but then I lose the semi-transparency on the shapes themselves.
    - I could place each of my Illustrator-generated animation frames onto a separate Keynote slide and have them auto Transition with no Effect – so use Keynote itself as the animation software – but for a halfway decent smoothness in the animation, we're talking a lot of frames and this approach seems pretty inefficient to me...  Not to mention a pain to do (as the image on each slide has to be independently aligned...  take me for ever!)
    For a relatively simple visual effect, this appears to be implausibly difficult to do...    Unless someone out there can see another way of doing it...
    Many thanks for any suggestions.

    Interesting idea...  I managed to achieve the effect I was after (I'll explain how below) only to realize that what I was actually aiming for was even harder than I had realized...
    What I am trying to animate is changing ethnic "territories" over time in South East Asia. These are complicated little shapes that merge into one another and shift about all over the place. As I am dealing with historical territorial (or perhaps more accurately, "distributional") data, I project it onto a purely physical map of Asia that has no modern political boundaries (as they are irrelevant). But this also means (if you are not so good at geography) that your normal visual reference points have gone, and for my students (French university-level language students, not geography majors) I'm sure that the result can be a little difficult to assimilate.
    For the past few years, I have been happily fading different, often visually disjunct arrangements into one another, but I have always been only moderately satisfied with the result: the changes can be hard to track visually, which defeats the whole purpose of displaying them this way...  I wanted the shapes to flow without interruption (like blobs of wax in a Lava lamp! - Theres an image for you!) – to be visually coherent.
    I began therefore thinking about morphing, and Flash animations...
    ...and ran into all the problems that the tiff between Apple and Adobe has currently left us with. (Don't you like the play on words there... tiff... )
    I gave up on trying to animate just the transparent blobs, with a view to overlaying the animation on a static blank map in Keynote, and instead tried animating the whole lot, background map and all, using Adobe Illustrator. The process involves Illustrator's blend tool, and exporting to .swf, then recapturing the .swf files with Snapz Pro X in .mov format, which allowed Keynote to import them.
    BUT! The result was still not what I wanted (picky, eh). Illustrator's blend tool does a superb job of translating any form into any other, no matter how complex, but groups of humans moving over land don't move like that! For instance, a circluar region moving to a coastal region, when "morphed" will progressively adopt the shape of the coastline before reaching it, which is just silly. It looks as if the population being represented distribute themselves to neatly match the coast when still about 500kms away (and over the space of several generations). Call me stickler, but it doesn't look right. It isn't right, and it's not what I need...
    Sure, any such representation is a vast oversimplification in any case, but superimposing such a specifically impossible visual trait onto the presentation runs counter to the whole idea of doing it for me. It should be iconically plausible (even if not accurate).
    So... I'm in a pause...  Looking to understand animating shapes better...
    I like your screen shot idea tho'. I will have to try it out...
    Cheers,
    Colin

  • How to add volume to simple shapes?

    How can I take simple rectangles like in the attached screenshot and add volume to them to give them more depth so the artwork is not flat. I tried playing with the extrude and bevel effects though was not able to do it. Any advice will be appreciated.
    Thanks.

    Orr draw half the shape path and use the Effevt>3D>Revolve that will give some options for positioning as well the abitilyt to map art to it.

  • Simple shape in white not printing

    I've never seen this before. I have a simple white shape with a logo on top.
    The shape itself sits on a coloured background.
    So far I only used this in a document and exported it as a pdf.
    But today I had to print the document and now it turns out it doensn't
    print the shape. I did a few tests in ID and AI. When I colour the shape
    any other colour then white it prints but as soon I colour it back to white
    the shape doesn't print anymore. I have a native postscript 3 printer.
    What on earth could be wrong?
    AI CS5.5
    ID CS5.5

    You might be interested in a plug-in called WhiteOP2KO (White Overprint To Knockout), from www.worker72a.com, that checks for White overprint in CMYK documents. They offer several versions with varying features (a free version that checks and puts up a findings dialog, a slightly less than free version that checks but doesn't say anything unless it finds something, and then a more full featured version that can actually fix problems).
    No connection; just a satisfied user.

  • Moving a divided shape(s) with one transition?

    hello forumers.
    ok i might be asking much,but im  just curious.is it possible since ive devided this square shape into 4 seperate shapes to move them all at once moving away from each other?i know its easy to do it with 4 divided squares.but what about when we want to divide an uneven shape and its divided into 20 seperate shapes.it would be tidious to manage each shape seperate.

    Not really but you can sort of do it in two steps
    you use the transform each and scale it say 125% in both directions then hit the exclude icon on the pathfinder panel
    step 1
    step 2
    I do not think this works with a circle. and distributing other shapes you would use two bends or two transform effects.

  • How do you draw simple shapes

    how do you dear simple shapes

    See After Effects Help: "Creating shapes and masks".
    Start here to learn After Effects: http://adobe.ly/bjBT3P

  • Beginner needs help, simple do-while

    Need some help whit this code, how can I get this do-while loop to work?
    I use a simple gui where a decimal number is been read in, and some calculations beeing done.
    I want the user to decide if he/she wants to exit or not.
    But I dont now how I shall use it when using the boolean type.
    Tanks in advance.
    I'm sorry about my bad english!
    import mittBibliotek.*;
    class nettopris{
         static final double moms = 1.24;
         static final double rabatt = .85;
         public static void main (String[] args){
              do{
                   JavabokGUI gui = new JavabokGUI("Legger til moms");
                   gui.show();
                   double pris = gui.lesDesimaltall("","Skriv inn nettopris: ");
                   if (pris>2000){
                        double rabattPris=bergenNypris(pris);
                        double brutto = beregnBruttopris(rabattPris);
                        double rabattbel?p= beregnRabbattBel?p(pris,rabattPris);
                        gui.skrivResultater("Nettopris - 15% rabatt : " +rabattPris);
                        gui.skrivResultater("Prisen inkl. mva : " +brutto);
                        gui.skrivResultater("Rabatt bel?pet er : " +rabattbel?p);
                        gui.skrivResultater("Mva bel?pet er : "+beregnMvabel?p(brutto,rabattPris));
                   }else{
                        double brutto= beregnBruttopris(pris);
                        double avrundetPris= avrunding(brutto);
                        gui.skrivResultater("Prisen inkl mva (avrundet): " +avrundetPris);
                        gui.skrivResultater("Mva bel?pet er (avrundet): " +beregnMvabel?p(avrundetPris,pris));
                   }// end if else
                   boolean svar = gui.jaSvar("","Ny beregning? ");// GUI  yes/no.Where yes is true.If true looping until false
    }while  (svar == true) ;// error: cannot resolve symbol, variabel svar
         }// main
         static double beregnBruttopris(double prisen){
              double brutto= prisen * moms;
              return brutto;
         }//Brutto
         static double avrunding(double bruttopris){
              int avrundet= (int) (bruttopris + 0.5);
              return avrundet;
         }// Avrundet
         static double bergenNypris(double nyprisen){
              nyprisen = nyprisen * rabatt;
              return nyprisen;
         }// Nyprisen
         static double beregnRabbattBel?p(double pris, double rabatt){
              double rabbel?p = pris - rabatt;
              return rabbel?p;
         }// Rabatt bel?p
         static double beregnMvabel?p(double brutton, double rabattPrisen){
              double mvaBel?p = brutton - rabattPrisen;
              return mvaBel?p;
         }// Mvabel?p
    } // class nettopris

    If your only problem is with the variable svar, just put a line:
    boolean svar = true;before the "do" line and change the line:
    boolean svar = gui.jaSvar("","Ny beregning? ");to:
    svar = gui.jaSvar("","Ny beregning? ");Your problem has to do with variable scope. Since you declare the variable svar inside the braces {} of the do loop, it doesn't exist for the while test.

  • Adding simple shapes and lines to a JPanel()

    If anybody out there knows how to add simple filled circles and then lines woth arrowheads connecting the 2 circles into a JPanel then please help me out???
    I have included my code below so you have an indication of what im doing:
    import java.awt.*;
    import java.awt.Graphics;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.Vector;
    import java.io.*;
    import java.util.Collections;
    public class rightSplitPane {
    private JSplitPane splitPane;
    private JPanel p1, p2;
         private String tran, res, type;
         private Graphics gr;
    public rightSplitPane() {         
    p2 = new JPanel();
    p2.setLayout(new BorderLayout());
    //gr = p2.getGraphics();
    //Graphics2D g2d = (Graphics2D) gr;
    //gr.drawLine(30, 40, 100, 100);
         //gr.drawRect(24, 10, 60, 60);
    //p2.repaint();
    JScrollPane topPane = new JScrollPane();
    topPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    topPane.getBorder();
              JScrollPane bottomPane = new JScrollPane(p2);
              bottomPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    bottomPane.getBorder();
    //Provide minimum sizes for the two components in the split pane
    Dimension size = new Dimension(625, 350);
    topPane.setMinimumSize(size);
    bottomPane.setMinimumSize(size);
    //Create a split pane with the two scroll panes in it
    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topPane, bottomPane);
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(350);
    topPane.getViewport().add(trTable, BorderLayout.CENTER);
    public JSplitPane getSplitPane() {
    return splitPane;
         public static void main(String args[]) {
              rightSplitPane test = new rightSplitPane();
    //HOW DO I GET THE SPLITPANE TO BE DISPLAYED TOO??
    } // end class

    I took out few lines:
    import java.awt.*;
    import java.awt.Graphics;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.Vector;
    import java.io.*;
    import java.util.Collections;
    public class rightSplitPane
         private JSplitPane splitPane;
         private JPanel     p1, p2;
         private String     tran, res, type;
         private Graphics   gr;
    public rightSplitPane()
         JScrollPane topPane = new JScrollPane();
         topPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    //     topPane.getBorder();
         p2 = new JPanel();
         p2.setLayout(new BorderLayout());
         JScrollPane bottomPane = new JScrollPane(p2);
         bottomPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    //     bottomPane.getBorder();
    //Provide minimum sizes for the two components in the split pane
         Dimension size = new Dimension(625, 350);
    //     topPane.setMinimumSize(size);
    //     bottomPane.setMinimumSize(size);
    //Create a split pane with the two scroll panes in it
         splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topPane, bottomPane);
         splitPane.setOneTouchExpandable(true);
         splitPane.setDividerLocation(350);
    //     topPane.getViewport().add(trTable, BorderLayout.CENTER);
    public JSplitPane getSplitPane()
         return splitPane;
    public static void main(String args[])
         rightSplitPane test = new rightSplitPane();
         JFrame frame = new JFrame();
         frame.setSize(700,500);
         frame.setContentPane(test.getSplitPane());
         frame.setVisible(true);
    /code]
    Noah                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Flash Freezes when doing simple Shape Tween

    I tested this in Flash 5 before I brought it over to Flash
    CS3 and am very concerned about the results.
    I have an object that has been created on the stage and is
    not a library item. I am creating an animation with no action
    scripting that will be converted to a mov file and the end use will
    be a video played on tv.
    I have three keyframes, spaced out at 1, 5, and 10 frames.
    Frame 10 has 10 nodes in the object, frame 5 has 8 nodes, and frame
    1 has 7 nodes. I put my playhead on any frame in between the
    keyframes, and cntl+click for the pop-up menu, from which I select
    'Create Shape Tween'. Flash creates the tween, but when I attempt
    to save or move the playhead (with either the 'return' key or the
    short cut keys) the program throws up the 'beach ball' which spins
    for over 5 minutes, making me 'force quit' the application.
    Other aspects of this project are that I have several layers
    (all of which are hidden [the 'eye' turned off] during testing),
    contained in a folder. No other animation has been applied to any
    other objects.
    I am running an iMac with version 10.4.11 and have had no
    other problems with the application.
    Is there a fix I can download? This seems to be a programming
    problem.
    Thank you for your help.

    Flash software has a major problem with some of the new
    tools, such as the Gradient Transform tool.

  • Simple shape fill question

    Ok ... i've been using photoshop since 1.0, and this has to be an elementary question - i'm just blanked.
    I drew a shape with the pen tool, closed it by clicking on the starting node.
    But the fill is "outside" the shape and not "inside".
    I've never seen this happen before  ...i've drawn literally thousands of shapes (tracing images etc as you would in illustrator or other vector-drawing programs).... what gives? how do i get the shape fill "inside" the shape and not "outside"?
    thanks.

  • Moving and resizing shapes .?!

    hey there ..
    i was wondering if you guys can help me figure out how to select , move and resize a specific shape .... apreciatte it a lot .. peace . take care and thanks for your concerns..

    Hi there, take a look at this code:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=427823
    You can view the working version at www.bhun.net/shapebean.html. The example isn't very complicated nor does it contain much functionality. But it does show you one way to handle the shapes (there are probably better ones). Resizing a shape just requires you to do some extra work.
    Greets
    nuhb

  • Moving a simple iostream program from g++ to gcc

    Hi,
    I have a simple program
    #include <iostream.h>
    main()
    cout << "Hello, world!\n";
    return 0;
    I've been using g++ to compile it. If I now use gcc instead, then it's not finding the libraries.
    can you please show me what to put in the following:
    from
    g++ -o example1 -Wno-deprecated -R/usr/local/lib example1.cc
    to
    gcc -o example1 -Wno-deprecated -R/usr/local/lib example1.cc
    but as it stands the command above using gcc doesn't work, while g++ does???/

    Thanks for the feedback.  Helpful info as we move forward.  We're starting to get the hang of what we've ventured into with the Windows machine.  Great performance.  Some foibles like the issues with codecs, but seems they may be at least a bit less of a problem than they first appeared.  One issue is our Adobe font library for our Macs.  Most of the fonts don't port over to the Windows side and that's a bit of a problem for an ad agency that tries to keep graphic /font consistency between our print and our video projects.
    Thanks again!

Maybe you are looking for

  • Audigy Platinum On Vi

    Im trying to get an audigy one platinum working with windows vista. I got the vista drivers from the creative website and installed. No problem. However i noticed the 'breakout box' in my dri'vebay wasnt working. So i checked device manager and I've

  • How to gain full access to an external HD

    I'm new to mac. My external HD is read only. How can I be able to add/delete files on it?

  • ALE WE19 ERROR

    I am trying to post a FI document using transaction code we19. Below are the steps that I have performed. The message type is FIDCC2. SCENARIO 1 - Without entering the business area. I enter the data into the segments and after checking the partner p

  • How to  convert  bill to party to sold to party

    hello... my client has asked to extend one customer who is in account group as bill to party( 0004) now i want to extend him as sold to party . can anybody please tell me about extend of a customer who are in  A/c groups ship to party bill to party p

  • HDD not detected during Windows 8 installation in UEFI

    ok well this is a little complicated to explain so m gonna summarize it as much as possible. i have a HP Sleekbook 15-B002xx which came with a windows 8 OS installed already. due to some reasons, i tried to shift it back to windows 7. After many unsu