Attaching MouseListeners to multiple graphics Objects ie rectangles

Can any one please help me by telling me how I can go about attaching mouselisteners to different rectangles in an application using one panel. I m not looking for code but any thing that my show me the way to this. Its very important that i do this.
Please help me
Sq2000

In the future, Swing related questions should be
posted in the Swing forum.
Maybe you just use a JPanel as a rectangle by setting
the border of the panel. Then you can add a
MouseListener to the panel.The code is as follows
import javax.swing.*;
   import java.awt.*;
   import java.awt.geom.*;
   import java.awt.image.*;
   import java.awt.event.MouseEvent;
     import javax.swing.event.MouseInputAdapter;
    class MapImager extends JPanel
           BufferedImage imageMap;
          private static JFrame frame = new JFrame();
           //private String botswana = "Images/botswana.jpg";
           private Rectangle2D.Double square =
           new Rectangle2D.Double(0, 0, 350, 350);
           private GradientPaint gradient =
           new GradientPaint(0, 0, Color.red, 175, 175, Color.yellow,true); // true means to repeat pattern
           private final static int SQUARE_EDGE_LENGTH = 10;
            private static JPanel panel;
            private static int xPos;
            private static int yPos;
            private static int xP;
          private static int yP;
          private MapPanel mapPanel;
           public MapImager (){
              //imageMap = getBufferedImage(botswana, this);
               xPos = 186;yPos = 100;
          static MouseInputAdapter mia = new MouseInputAdapter(){
               public void mousePressed(MouseEvent e){
                    xPos = e.getX();
                   System.out.println(" The X2 When mousePressed Cordinates are "+xPos);
                   yPos = e.getY();
                   System.out.println(" The Y2 When mousePressed Cordinates are "+yPos);
                   frame.repaint();
               public void mouseDragged(MouseEvent e){
                    xPos = e.getX();
                   System.out.println(" The X2 When mouseDragged Cordinates are "+xPos);
                   yPos = e.getY();
                   System.out.println(" The Y2 When mouseDragged Cordinates are "+yPos);
                   frame.repaint();
           public void paintComponent (Graphics g){
             Graphics2D g2d = (Graphics2D)g;
             this.setBackground(Color.WHITE);
               g2d.setPaint(gradient);
               g2d.fill(square);
                 g2d.drawImage (imageMap, 0, 0, this);
               g.setColor(Color.RED);//I want to draw as many as i want and have each move freely on the frame.
               g.fillRect(xPos-(SQUARE_EDGE_LENGTH/2), yPos-(SQUARE_EDGE_LENGTH/2), SQUARE_EDGE_LENGTH, SQUARE_EDGE_LENGTH);
     public static BufferedImage getBufferedImage(String imageFile,Component c){
         Image image = c.getToolkit().getImage(imageFile);
         waitForImage(image, c);
         BufferedImage bufferedImage =
            new BufferedImage(image.getWidth(c), image.getHeight(c),
                        BufferedImage.TYPE_INT_RGB);
         Graphics2D g2d = bufferedImage.createGraphics();
         g2d.drawImage(image, 0, 0, c);
         return(bufferedImage);
     public static boolean waitForImage(Image image, Component c){
         MediaTracker tracker = new MediaTracker(c);
         tracker.addImage(image, 0);
         try {
            tracker.waitForAll();
             catch(InterruptedException ie) {}
         return(!tracker.isErrorAny());
       public static void main(String[] args){
              MapImage map = new MapImage();
              frame.add(map);
               frame.addMouseListener(mia);
               frame.addMouseMotionListener(mia);
             frame.setSize(360, 380);
              frame.setTitle("Map of Botswana");
              frame.setVisible(true);
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }Sq2000

Similar Messages

  • Painting multiple graphic objects

    Hi, I need to create something where I can paint rectangles and circles etc on a canvas.
    Almost like MS Paint.
    I guess I must use a JComponent to paint on, but my problem is how does it store all previously painted objects, e.g if i draw 3 rectangles, the minimize and maximize the window (i.e call update()), only the last rectangle is visible.
    Must I store everything in an array, and then traverse it everytime update() is called ?
    Surely there must be an easier way ?

    There is one, it called BufferedImage, you create one then get it graphics, draw on it every time you want (not in the pain method), and in the paint method you draw this bufferedimage to the graphics.
    BufferedImage b1;
    Graphics g1;
    b1 = new BufferedImage(w,h,BufferedImage.TYPE_3BYTE_BGR);
    g1 = b1.getGraphics();
    g1.setColor(Color.red);
    g1.drawRect(100,100,100,100);
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    g.drawImage(b1,0,0,null);
    Noah

  • Multiple graphics objects?

    Is there any way to plot different graphs in multiple Xmath Graphics windows?  I know that the graphics window can be divided into a matrix of subplots, but what I'd like to do is plot two graphs in one window and a third graph in a second window.  I know in MATLAB, you can do subplots as well as plotting multiple figures in different windows.  Does MATRIXx have anything like this?
    Alternatively, is there any way to subdivide the graphics window into two rows and two columns with one plot stretched across both columns of the first row and two smaller graphs taking the spots { row = 2, column = 1 } and { row = 2, column = 2 }?  For the first plot, I tried doing something like { row = 1, column = [ 1, 2 ] }, but the debugger informed me that keyword column only accepts integer values.
    Thanks,
    Luke G.

    Hi Luke,
    Yes, Xmath does support multiple plot windows. You have to use the Plot2D command for multiple windows, using the {win=num} option.
    To plot graphs in subplot areas, use the {posn=[numrows,numcols,row,col,rowspan,colspan]} option. This syntax works in both Plot and Plot2D and does exactly what you want.
    Dirk

  • Zoom a 2D graphic object

    we can zoom a 2D graphic object by scale x,y coordinates.
    For instance, a rectangle will be enlarged to double size by doubling the coordinates,
    My question is to seek the idea of keeping the object size unchanged but zoom the inside detail?
    Just like mapquest,click zoom button more details will be clearly seen but the frame size unchanged?
    Thanks

    There are a couple of solutions to this that I can think of.
    The first would be to have bitmaps prerendered at multiple resolutions with all the detail necessary for that resolution, and then display the lowest resolution image that gives the greatest amount of detail for the resolution needed by the application at the time. This method is used in 3d graphics programs to show lower detail textures on objects that are farther away.
    For very high magnifications, the large images may have to be partitiioned into multiple subimages, and of course you would only display the ones necessary to fill the viewing window.
    The other method would be to not use bitmaps at all, but store things as Shapes, which you can scale as required via an appropriate AffineTransform as necessary.
    These two methods are not at all mutually exclusive, so combining them and using bitmaps in one area and scaled shapes in another is entirely possible.

  • Querying for a script insert multiple selected objects...

    Is there a script or plugin which insert multiple selected objects in one new text frame with one click?
    And is there a script or plugin which extract the content of anchored text frame out it's frame and replace it with it's frame. and extract selected text and insert it inside a new anchored text frame in it's place? (like convert text to table - convert table to text, but instead table we use text frame)

    Hi,
    Using OMB scripting to set attribute properties in a data mapping sort of defeats the purpose of utilizing a graphical user interface to define and set properties for a data mapping? Surely the GUI data mapping tool was created to get away from writing scripts and scripting would also require that you know the name of the data mapping, table operator and the set of attribute names for which you have to write one line of script to set each property value, i.e. 90 lines to set 90 attribute values.
    Cheers,
    Phil

  • Multiple resource objects provision issue in OIM10g

    Hi Team,
    We're facing an issue regarding multiple access policy trigger for a specific resource object in OIM.
    The scenario is whenever we try to process the enablement or creation of users through flat file recon, users are created / enabled with multiple resource objects in their resource profiles.
    When we checked in User Resource Access History report, we observe that the access policy has been triggering multiple times for these users resulting in users with multiple resource objects. Amongst these one shows provisioned/Enabled and the other shows provisioning/in some cases Provisioned/Enabled.
    Please advise as this has become an ongoing issue and also has led into data mess-up.
    Appreciate your help on this one..
    Regards,
    Sagar

    The terminology sounds a little confusing to me:
    If you mean you wanna create multiple IT Resources for a single IT Resource Instance so that the user can select the appropriate IT Resource during request creation -> All good upto here. But then since the Object/Request Form attached to a resource would be the same, so any user would always see the same form fields for creationg request.
    Example: Users creating request for Oracle Database Accounts but different server locations
    If it means you just need to create multiple Resource Objects then its a straighaway standard requirement and could be handled with normal Connector Development methodology.
    Example: Users creating requests for different resources like Oracle Database Accounts & Active Directory Accounts

  • How does one Float a Graphic Object with Text? (Don't want the Graphics Frame stationary)

    I now know just enough InDesign to be dangerous.  So, help me from blowing myself up.
    SITUATION:
    I desire a Callout/Quote Box to emphase a quote--to separate it from the flowing text of the manuscript.  So, I created a curved-edge rectangle (graphic object) to make the "box", then filled it with the quoted text).  All was well in the land of Adobe Novice UNTIL I deleted some text above the newly-created graphic box/quote box.  I need the graphic to flow with (stay embedded in; hold its position in) the text outside the manuscript, not say anchored to page.
    QUESTION:
    Is there a way to have a graphic object which is placed in a manuscript flow with the manuscript text, so that it "holds its position" relative to the text.  For example, if I delete a paragraph of text above the graphic object, I want the graphic object to adjust accordingly.
    ASIDE:
    I am open to any other tricks or methods others use to insert callout or quote-boxes within the flowing text of a manuscript/book.
    Thanks in advance.

    Create your callout. If you will use it often, you can actually grab it and drag it to the desktop for reuse in any Document; it becomes an InDesign Snippet (.inds).
    Copy the callout graphic, insert your text curser into the text frame where you want the callout. You've just Anchored an Object.
    This is where you want to read up on Anchored Objects. You can highlight and baseline shift the callout (often necessay for anchored objects) , change leading, apply text wrap with standoff (you would select it with the selection tool for this), all of which are way beyond what I have ever tried, but managed it in less than 3 minutes. Basically treat it as a selection of type. The challenges will be line breaks, keep with, gosh knows.
    Bob mentioned CS5.5 has more friendly features, which I am not familiar with, and are beyond quick replies.
    Work through the above at your discretion, ask more DIRECT questions as needed, and you will get help. 

  • Tooltips over graphics objects

    Hi All
    Hope you all had a merry Christmas.
    Does anyone know if i can add a tooltip to a graphics objects?
    Basically i am drawing a series of rectangles in a JPanel and when i hover my mouse over each rectangle i want a different tip to display...however if i use the setToolText() method it sets it for the entire JPanel? any ideas?

    tooltip-like popup with mouseover

  • [CS2/CS3] - Browsing all inline graphical objects

    Hello,     I have a text frame, where are placed inline graphical objects (square, circle, ...) and I want to browse all these objects.<br/><br/>
    Sample:
    I have valid UIDRef to entire text frame, but when I use this code:
    InterfacePtr<IHierarchy> hierarchy(textFrameUIDRef, UseDefaultIID());
    int32 childCount = hierarchy->GetChildCount();
    value of childCount == 1, when I use recursive call to get child I am given also value "1" and this node has no children.
    Thank you for your help !

    Thank you for your answers,
       I followed your advices and I browsed code from "CodeSnippet", where is an access to get OwnedItemStrands.
    According the attached snapshot from Programming Guide (p. 375), I am able to get kSplineItemBoss, that is fine, but I need to skip from Text fundamentals to Graphical fundamentals. I need to be able to catch ISpread interface of graphical objects?
    Thank you, marxin

  • Canvas - Graphic object properties

    The problem is as following:
    I’ve got a form where objects are situated on two tab pages. A number of text_items are placed on rectangle graphic objects. My goal is to control visibility of those objects depending on certain conditions:
    With text items correctly works:
    QUANTITY_ID ITEM;
    QUANTITY_ID := find_item('PRODUCT.QUANTITY');
    set_item_property (QUANTITY_ID, visible, property_false);
    With graphics object I’m facing the problem with reaching the item:
    G_QUANTITY_ID ITEM;
    G_QUANTITY_ID := find_item('?????????????.G_QUANTITY');
    Placement of the object:
    Forms -> Canvases -> Tab Pages -> [Product] -> Graphics -> [G_QUANTITY]
    Where:
    [Product] – Name of the tab page
    [G_QUANTITY] – Rectangle graphic object
    I’ll appreciate any kind of help. Thanks in advance.

    Hello,
    There is no available built-in concerning the graphic objects displayed on the canvas. All you can do use another stacked canvas to show/hide the graphic objects located on it.
    Francois

  • (261718088) Q: Can you use xm:multiple with Objects other than String?

    Q: Can you use xm:multiple with Objects other than Strings?
    <br>
    A: You bet. Attached find a text file with some code from the example I showed
    today, a version of the multipleSayHiTo() method that has a parameter of an Array
    of Person objects rather than a parameter of an Array of Strings. The code within
    the text file comes from the Greeting.jws file (the Greeting Web Service).
    [multiple.txt]

    So you are saying that the recovery discs I made do include the copy of windows that was originally installed?
    Absolutely! They will restore the hard disk to its original out-of-the-box contents. Follow the instructions in the section Restoring from recovery DVDs/media, which begins on p. 73 of the User's Guide.
       Satellite A660 Series User’s Guide
    maybe i can make a deal with wd to have them swap this drive out for the BEKT instead...
    That would be a good idea in any case.
    As I said, the 10-fc12-045d error would not be due to the drive's being AFT, but more likely the discs are not being read properly. New discs can be obtained from Toshiba. Scroll down to Get Recovery Media here
    -Jerry

  • Adding Multiple Opportunity Objects to a Contact Object

    According to the documentation, the Contact Object has the following Child components: Account, Activity, Address, Asset, Attachment, Book, Campaign, CustomObject3, Interests, Lead, Note, Opportunity, Related Contact, Revenue, Service Request and Team.
    Via the Contact WSDL, I see that there are properties for everything else BUT Opportunity. How would I associate multiple Opportunity objects to a Contact if there isn't a ListOfOpportunity property?
    ListOfAccount
    ListOfAccountRole
    ListOfActivity
    ListOfAddress
    ListOfAttachment
    ListOfClaim
    ListOfContactBestTimes
    ListOfContactLicense
    ListOfCoverage
    ListOfCustomObject10
    ListOfCustomObject11
    ListOfCustomObject12
    ListOfCustomObject13
    ListOfCustomObject14
    ListOfCustomObject15
    ListOfCustomObject4
    ListOfCustomObject5
    ListOfCustomObject6
    ListOfCustomObject7
    ListOfCustomObject8
    ListOfCustomObject9
    ListOfDealRegistration
    ListOfFinancialAccount
    ListOfFinancialAccountHolder
    ListOfFinancialPlan
    ListOfInterests
    ListOfInvolvedParty
    ListOfLead
    ListOfNote
    ListOfObjectives
    ListOfPlanContact
    ListOfPolicy
    ListOfPolicyHolder
    ListOfRelatedContact
    ListOfRevenue
    ListOfServiceRequest
    ListOfSignature
    ListOfTeam

    That is exactly what I did. It worked! Thank you.
    Here's how I did it:
    using (Opportunity proxy = new Opportunity())
    proxy.Url = Session.WebserviceUrl;
    OpportunityWS_OpportunityInsertChild_Input parent = new OpportunityWS_OpportunityInsertChild_Input();
    parent.ListOfOpportunity = new Opportunity1[1];
    parent.ListOfOpportunity[0] = new Opportunity1();
    parent.ListOfOpportunity[0].ExternalSystemId = claimant.ExternalSystemId;
    parent.ListOfOpportunity[0].ListOfContact = new Contact[physicianList.Count];
    foreach (Physician physician in physicianList)
    int i = physicianList.IndexOf(physician);
    parent.ListOfOpportunity[0].ListOfContact[i] = new Contact();
    parent.ListOfOpportunity[0].ListOfContact.ExternalSystemId = physician.ExternalSystemId;
    }//end foreach
    proxy.OpportunityInsertChild(parent);
    }//end using

  • New technique to place multiple anchored objects in InDesign story

    Hello,
    For a while I have been trying to figure out how to insert multiple anchored objects into an Indesign story. As far as I can tell, you cannot copy multiple objects that have already been placed in a document (such as a multi-page pdf) into an InDesign story, but must copy and paste them one-by-one into the story. This is a problem for a project I am working on where I want to have a large number of 340x52 pt pdfs to flow throughout a document in a master text frame interspersed with text.
    I have now found a solution for this issue that I thought I would share in case it would be helpful for anyone. It utilizes Automator actions for Mac OS X and Microsoft Word 2011 [2008 may work also, but I don't have a copy of that to test]; I am not good with scripting but perhaps similar solutions could be found for other systems and programs.
    1. If you want to place a multipage pdf within a text frame, first it into individual files for each page (with Acrobat Pro or pdftk or something similiar).
    2. Create an Automator service or program with the action "Create New Word Document". You can also use another automator action to save the document, or save it manually (to change the filename). In the finder, select the items you want, then run the service or drag them into the Automator program you have created.
    3. Place the word document into your InDesign story. Your items will now be anchored objects ordered in your text frame as they were in the finder.
    Please let me know if this is helpful or if anyone has suggestions for doing this process is a more efficient way. I am not sure, but it may be the case that this approach would only work on Macs, as I gather from this thread.

    I might note that I am using InDesign CS 5, and importing from a document stored in docx format.

  • How to change font/ font color etc in a graphic object using JCombobox?

    Hello
    My program im writing recently is a small tiny application which can change fonts, font sizes, font colors and background color of the graphics object containing some strings. Im planning to use Jcomboboxes for all those 4 ideas in implementing those functions. Somehow it doesnt work! Any help would be grateful.
    So currently what ive done so far is that: Im using two classes to implement the whole program. One class is the main class which contains the GUI with its components (Jcomboboxes etc..) and the other class is a class extending JPanel which does all the drawing. Therefore it contains a graphics object in that class which draws the string. However what i want it to do is using jcombobox which should contain alit of all fonts available/ font sizes/ colors etc. When i scroll through the lists and click the one item i want - the graphics object properties (font sizes/ color etc) should change as a result.
    What ive gt so far is implemented the jcomboboxes in place. Problem is i cant get the font to change once selecting an item form it.
    Another problem is that to set the color of font - i need to use it with a graphics object in the paintcomponent method. In this case i dnt want to create several diff paint.. method with different property settings (font/ size/ color)
    Below is my code; perhaps you'll understand more looking at code.
    public class main...
    Color[] Colors = {Color.BLUE, Color.RED, Color.GREEN};
            ColorList = new JComboBox(Colors);
    ColorList.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                     JComboBox cb = (JComboBox)ev.getSource();
                    Color colorType = (Color)cb.getSelectedItem();
                    drawingBoard.setBackground(colorType);
              });;1) providing the GUI is correctly implemented with components
    2) Combobox stores the colors in an array
    3) ActionListener should do following job: (but cant get it right - that is where my problem is)
    - once selected the item (color/ font size etc... as i would have similar methods for each) i want, it should pass the item into the drawingboard class (JPanel) and then this class should do the job.
    public class DrawingBoard extends JPanel {
           private String message;
           public DrawingBoard() {
                  setBackground(Color.white);
                  Font font = new Font("Serif", Font.PLAIN, fontSize);
                  setFont(font);
                  message = "";
           public void setMessage(String m) {
                message = m;
                repaint();
           public void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  //setBackground(Color.RED);
                  Graphics2D g2 = (Graphics2D) g;
                  g2.setRenderingHint             
                  g2.drawString(message, 50, 50);
           public void settingFont(String font) {
                //not sure how to implement this?                          //Jcombobox should pass an item to this
                                   //it should match against all known fonts in system then set that font to the graphics
          private void settingFontSize(Graphics g, int f) {
                         //same probelm with above..              
          public void setBackgroundColor(Color c) {
               setBackground(c);
               repaint(); // still not sure if this done corretly.
          public void setFontColor(Color c) {
                    //not sure how to do this part aswell.
                   //i know a method " g.setColor(c)" exist but i need to use a graphics object - and to do that i need to pass it in (then it will cause some confusion in the main class (previous code)
           My problems have been highlighted in the comments of code above.
    Any help will be much appreciated thanks!!!

    It is the completely correct code
    I hope that's what you need
    Just put DrawingBoard into JFrame and run
    Good luck!
    public class DrawingBoard extends JPanel implements ActionListener{
         private String message = "message";
         private Font font = new Font("Serif", Font.PLAIN, 10);
         private Color color = Color.RED;
         private Color bg = Color.WHITE;
         private int size = 10;
         public DrawingBoard(){
              JComboBox cbFont = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
              cbFont.setActionCommand("font");
              JComboBox cbSize = new JComboBox(new Integer[]{new Integer(14), new Integer(13)});
              cbSize.setActionCommand("size");
              JComboBox cbColor = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbColor.setActionCommand("color");
              JComboBox cbBG = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbBG.setActionCommand("bg");
              add(cbFont);
              cbFont.addActionListener(this);
              add(cbSize);
              cbSize.addActionListener(this);
              add(cbColor);
              cbColor.addActionListener(this);
              add(cbBG);
              cbBG.addActionListener(this);
         public void setMessage(String m){
              message = m;
              repaint();
         protected void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setColor(bg);//set background color
              g2.fillRect(0,0, getWidth(), getHeight());          
              g2.setColor(color);//set text color
              FontRenderContext frc = g2.getFontRenderContext();
              TextLayout tl = new TextLayout(message,font,frc);//set font and message
              AffineTransform at = new AffineTransform();
              at.setToTranslation(getWidth()/2-tl.getBounds().getWidth()/2,
                        getWidth()/2 + tl.getBounds().getHeight()/2);//set text at center of panel
              g2.fill(tl.getOutline(at));
         public void actionPerformed(ActionEvent e){
              JComboBox cb = (JComboBox)e.getSource();
              if (e.getActionCommand().equals("font")){
                   font = new Font(cb.getSelectedItem().toString(), Font.PLAIN, size);
              }else if (e.getActionCommand().equals("size")){
                   size = ((Integer)cb.getSelectedItem()).intValue();
              }else if (e.getActionCommand().equals("color")){
                   color = (Color)cb.getSelectedItem();
              }else if (e.getActionCommand().equals("bg")){
                   bg = (Color)cb.getSelectedItem();
              repaint();
    }

  • Not possible to store multiple fileReference object in same array?

    Hi all,
    I'm trying to store multiple fileReference  object in one array. But everytime I push() in a new object the old  objects that's already in the array gets set to the latest object.
    I'm  letting the user select an image. Then I push the selected  fileReference object into an array like my_array.push(  FileReference(event.target) );
    If I then run a loop on  "my_array" to check it's content I'm getting the latest pushed  fileReference object for every index in the array.
    With one object pushed in:
    1. Image1.jpg
    With two objects pushed in:
    1. Image2.jpg
    2. Image2.jpg
    Anyone have any thoughts on this?
    Thank you so much

    This is basically what I'm doing. The code is cut out from a larger portion so there might be errors, but hopefully not.
    // Local Files
    private var localFiles:FileReference           = new FileReference();
    private var fileList:Array                = new Array();
    private function browse(event:MouseEvent)
         trace("[Browse] Using local files");
         localFiles.addEventListener(Event.SELECT, onLocalFilesSelected);
         localFiles.browse(getAllowedTypes());
    * LOCAL FILE
    private function onLocalFilesSelected(e:Event)
         localFiles.addEventListener(Event.COMPLETE, localFileHandler);
         localFiles.load();
    private function localFileHandler(event:Event):void
         localFiles.removeEventListener(Event.COMPLETE, localFileHandler);
         fileList.push(FileReference(event.target));
         showFileList();
    private function showFileList():void
         for(var $x:int=0;$x<fileList.length;$x++)
              var file:FileReference = FileReference(fileList[$x]);
              trace($x+": " + file.name);
    Thank you

Maybe you are looking for