Detecting object component

I'm writting an applet in which there're 3 objects(same class) on the screen, when I clicked and dragged the object, it'll move along with the mouse. I'm having trouble to let the mouse recognise which object it is clicked and dragged. Can anyone please help me? I'm new to Java and I need to slove this problem as soon as I can. Thanks!

It would greatly help with some source code :D
But anyway, here is one solution:
If you add a x and y variable into each class and make the mouseDragged event change these variables.
Then you could use
p1.setLocation(p1.x, p1.y);or maybe even from inside the class
setLocation(x, y);

Similar Messages

  • Mouse detecting object component

    I'm writting an applet in which there're 3 objects(same class) on the screen, when I clicked and dragged the object, it'll move along with the mouse. I'm having trouble to let the mouse recognise which object it is clicked and dragged. Can anyone please help me? I'm new to Java and I need to slove this problem as soon as I can. Thanks!

    You didn't say what kind of objects you are trying to move. Looking at your earlier threads it appears you were working with graphics (as opposed to components like Panels or Labels). Here's an example of detecting and moving graphic shapes in the AWT. Swing is a little easier to do this in because of the double buffering. I made it so you can run it in either j2se 1.4 or the newer 1.5 (which requires generics).
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.event.MouseInputAdapter;
    public class Detection
        public Detection()
            DetectionPanel detectionPanel = new DetectionPanel();
            Detector detector = new Detector(detectionPanel);
            detectionPanel.addMouseListener(detector);
            detectionPanel.addMouseMotionListener(detector);
            Frame f = new Frame();
            f.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            f.add(detectionPanel);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        public static void main(String[] args)
            new Detection();
    class DetectionPanel extends Panel
        List <RectangularShape> shapes;                                     // j2se 1.5
        // List shapes;                                                     // j2se 1.4
        boolean firstTime;
        public DetectionPanel()
            shapes = new ArrayList<RectangularShape>();                     // j2se 1.5
            // shapes = new ArrayList();                                    // j2se 1.4
            firstTime = true;
        public void paint(Graphics g)
            super.paint(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(firstTime)
                initShapes();
            for(int j = 0; j < shapes.size(); j++)
                g2.draw(shapes.get(j));                                     // j2se 1.5
                // g2.draw((RectangularShape)shapes.get(j));                // j2se 1.4
        private void initShapes()
            int w = getWidth();
            int h = getHeight();
            int dia = Math.min(w,h)/4;
            shapes.add(new Rectangle(2*w/3, 2*h/3, dia, dia));
            shapes.add(new Ellipse2D.Double(w/4 - dia/2, h/3 - dia/2, dia, dia));
            firstTime = false;
        public void moveShape(int index, int x, int y)
            RectangularShape rs = shapes.get(index);                        // j2se 1.5
            // RectangularShape rs = (RectangularShape)shapes.get(index);   // j2se 1.4
            Rectangle clip = new Rectangle();
            clip.x = (int)(x < rs.getX() ? x : rs.getX());
            clip.y = (int)(y < rs.getY() ? y : rs.getY());
            clip.width  = (int)(clip.x + rs.getWidth());
            clip.height = (int)(clip.y + rs.getHeight());
            rs.setFrame(x, y, rs.getWidth(), rs.getHeight());
            repaint(clip.x, clip.y, clip.width, clip.height);
        public List<RectangularShape> getShapes()                           // j2se 1.5
        // public List getShapes()                                          // j2se 1.4
            return shapes;
    class Detector extends MouseInputAdapter
        DetectionPanel detectionPanel;
        int selectedIndex;
        Point offset;
        boolean dragging;
        public Detector(DetectionPanel dp)
            detectionPanel = dp;
            offset = new Point();
            dragging = false;
        public void mousePressed(MouseEvent e)
            Point p = e.getPoint();
            List<RectangularShape> list = detectionPanel.getShapes();       // j2se 1.5
            // List list = detectionPanel.getShapes();                      // j2se 1.4
            for(int j = 0; j < list.size(); j++)
                RectangularShape rs = list.get(j);                          // j2se 1.5
                // RectangularShape rs = (RectangularShape)list.get(j);     // j2se 1.4
                if(rs.contains(p))
                    offset.x = (int)(p.x - rs.getX());
                    offset.y = (int)(p.y - rs.getY());
                    dragging = true;
                    selectedIndex = j;
                    break;
        public void mouseReleased(MouseEvent e)
            dragging = false;
        public void mouseDragged(MouseEvent e)
            if(dragging)
                int x = e.getX() - offset.x;
                int y = e.getY() - offset.y;
                detectionPanel.moveShape(selectedIndex, x, y);
    }

  • How to detect object being touched or not in kinect

    Dear all,
    i am new bie to kinect programming. i want to build application where camera can detect object touched or not.consider 3 object are placed on table like in set book ; remote & MOUSE . whenever object being picked i wanted to increment paricular item
    being counted up. if object kept back count remain same. 
    Is it possible to check which object being touched?? & increment the count in the particular item section.
    if moused picked once increment mount count value by 1 & display on screen.let me know how can i do usinf kinect sensor.
    AMPS12

    Kinect itself does not provide any type of object recognition. There are third party libraries and tools that you may want to look into that can do that. Kinect will only provide you depth and color information of what the camera sees. We have a body tracking
    system so we know where people are. Based on that and if you define target areas, you may be able to deduce things.
    Carmine Sirignano - MSFT

  • Detecting object in images

    Hi,
    how can I detect objects in images using java ?
    I need to detect movements of an object in consecutive images exported from a video.
    thank you

    use PixelGrabber to record a grid of colors then store it in a 2D array and with the next image get another 2D array of colors from the picture and compare the two arrays to see which part of the grid changed. You still will not have a way to tell the difference from the place were the object was and the color of the current object unless you had a image of the place room screen or what ever it is without objects and compared all other images to that one.

  • Detecting objects in images

    http://richandsian.co.uk/images/testin.png - Input image
    http://richandsian.co.uk/images/testout1.png - Output image 1
    http://richandsian.co.uk/images/testout2.png - Output image 2
    http://richandsian.co.uk/errata/blobdimensions.txt - Object dimensions
    Ok, so I'm trying to play with something like OCR that I've written, but very simple. It just looks for groups of connected pixels by thresholding an image and seeing who is connected, then paints each blob a random colour.
    When I then spit out details about the height and width of each blob (see object dimensions) I get mostly sensible stuff - characters of width 5x7 for ones like aeuonmcv, etc... and the odd 5x10 you would think might be an h,p,g,d, etc...all good.
    However, I have the odd blob that's something bizarre like 55x3 and not an obvious object looking at the image. So I painted all blobs their own colour only if they had a dimension greater than 10.
    And this: http://richandsian.co.uk/images/testout3.png is what I got.
    Presumably there's a pattern to what I've done, but I can't figure it out, anyone have any ideas? Thanks
    Code tarball here: http://richandsian.co.uk/errata/ocr.tar.gz

    Hi cs02rm0,
    I read the post and am trying to do something similar, is there any chance I could get a look at the code? Many thanks, Ron

  • How to properly detect object not found in query?

    Generally, we'd prefer to catch the unchecked exceptions which JDO throws in
    response to database operations that go awry. That said, there's one in
    particular that's bothering us:
    The most important and common one of these which we'd like to know about is
    when a query or getObjectByID() fails because the desired object isn't in
    the DB.
    Currently, an exception is thrown, which we would presumably have to catch
    and parse the message text of to determine if this was a row not found, vs.
    a database problem?
    Please tell me there's a better way to determine if a row(s) isn't(aren't)
    found!
    thanks,
    david

    Patrick -- I believe we just see them in getObjectById(), which is what we
    do most often.
    The subclass of JDODataStoreException that you'll throw is great.
    I'd suggest that a property setting could configure kodo to return null to
    getObjectById() instead -- ONLY for the case of object not found, for those
    of us who might consider this a less-than-truly-exceptional case :)
    thanks much,
    david
    "Patrick Linskey" <[email protected]> wrote in message
    news:[email protected]..
    David,
    Also, a query should return a collection of size zero, and not throw an
    exception.
    Are you seeing exceptions only when executing getObjectById(), or also
    when querying?
    -Patrick
    On Tue, 29 Apr 2003 05:03:23 -0400, david michaels wrote:
    Generally, we'd prefer to catch the unchecked exceptions which JDO
    throws in response to database operations that go awry. That said,
    there's one in particular that's bothering us:
    The most important and common one of these which we'd like to know about
    is when a query or getObjectByID() fails because the desired object
    isn't in the DB.
    Currently, an exception is thrown, which we would presumably have to
    catch and parse the message text of to determine if this was a row not
    found, vs. a database problem?
    Please tell me there's a better way to determine if a row(s)
    isn't(aren't) found!
    thanks,
    david--
    Patrick Linskey
    SolarMetric Inc.

  • Associating records of processes N its subprocess in data object COMPONENT

    Hi,
    I am using Monitor Express to monitoring BPM process data, and I want to group data from a process and its subprocess.
    How to join these informations if there is no key-field in COMPONENT dataobject (COMPOSITE_INSTANCE_ID and COMPONENT_INSTANCE_ID are different between processes and subprocess).
    Luciano Gomes

    Hi,
    I am using Monitor Express to monitoring BPM process data, and I want to group data from a process and its subprocess.
    How to join these informations if there is no key-field in COMPONENT dataobject (COMPOSITE_INSTANCE_ID and COMPONENT_INSTANCE_ID are different between processes and subprocess).
    Luciano Gomes

  • BO Extension - how to detect object deletion?

    Hi community.
    I have the problem that we extended an SAP BO node and this BO node might get deleted by user interaction using SAP floorplans.
    However to prevent associations from our custom BOs to this extended SAP BO node pointing into the void I need to somehow react on deletion of this BO node.
    Our own floorplans following these associations and showing content from the SAP BO node throw exceptions if the SAP BO node does not exist anymore.
    the afterModify or beforeSave events of the extended BO do not work: both are (afaik) not triggered upon deletion.
    Did anybody else encounter a similar problem and maybe found a solution?
    More specific: we exended the SAP Project BO and have trouble when a ProjectTask is deleted.

    Hi Sunil, thanks for your answer.
    I already to check for IsSet on the ProjectTask but the assoviation was set even though the destination object was not existent anymore.
    The Idea about counting the project tasks is a good additional idea, i will try to explore into this direction.
    However, how could I solve the problem when the exception gets thrown by UI?
    I.e. when viewing floorplans (no changes made to object so far -> no events/actions with custom code triggered) the UI interpreter follows these associations and tries to load the relevant object to show  the project task data.
    I might save a local copy of this data maybe...
    Best regards,
    Ludger

  • Detecting Active Component in a BOM

    Hello guys,
    Wanted to know if there is an easy way to know which componentes in a BOM are the active ones? A way not involving comparing validation date, like if there is a yes or no something that tells me those components in the BOM are the active ones, the others are the alternative or the old ones.
    Regards,

    Hi,
    can you please elaborate your requirement
    what do you mean by active?
    are you looking some thing like if the component are production or costing relevant?
    Regards,
    Shaiil

  • Detect object property change

    public class Obj
      public String obj_prop= null;
    Obj obj = new Obj();
    obj.obj_prop = "test";//How can I detect (inside class Obj ) that obj_prop  has changed ?Edited by: BubikolRamiosq3ERQ3WTS on Feb 25, 2010 8:51 AM

    You can't. Solution: don't expose variables like that, hide them behind getter and setter methods, that way you can write whatever code you like to run whenever something else changes the value

  • Determing which component from a custom TreeCellRenderer was clicked on

    hi,
    i've been experimenting with finding which component has been clicked on in a JTree which has a custom tree cell renderer. I've got a piece of code that appears to work, but am unsure if this is the proper way to go about doing this, and whether it might fail under some circumstances.
    any help appreciated,
    asjf
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class JTreeTest1 {
       public static void main(String[] arg) throws Exception {
          final JTree tree = new JTree();
          final TreeCellRenderer renderer = new MyRenderer();
          tree.setCellRenderer(renderer);
          tree.addMouseListener(new MouseAdapter() {
             public void mouseClicked(MouseEvent e) {
                int x = e.getX(), y = e.getY();
                int row = tree.getRowForLocation(x,y);
                TreePath path = tree.getPathForLocation(x,y);
                if(path!=null) {
                   Object o = path.getLastPathComponent();
                   Rectangle r = tree.getPathBounds(path);
                   // how to detect what component has been clicked on?
                   // simplification: pretend all boolean state has no effect on renderer (which is true for the renderer below)
                   Component renderedComponent = renderer.getTreeCellRendererComponent(tree, o, false, false, false, row, false);
                   renderedComponent.setBounds(r);
                   int _x = (int) ((double)e.getX() - r.getX());
                   int _y = (int) ((double)e.getY() - r.getY());
                   Component clickedUpon = SwingUtilities.getDeepestComponentAt(renderedComponent, _x, _y);
                   if(clickedUpon instanceof JLabel) {
                      JLabel jl = (JLabel) clickedUpon;
                      System.out.println(jl.getText());
          JFrame frame = new JFrame("JTreeTest1");
          frame.getContentPane().add(tree);
          frame.pack();
          frame.setVisible(true);
    class MyRenderer extends JPanel implements TreeCellRenderer {
       JLabel custom;
       public MyRenderer() {
          super(); // flow layout
          add(new JLabel("Hello"));
          add(custom = new JLabel());
          custom.setOpaque(true);
          custom.setBackground(UIManager.getColor("Tree.background"));
          custom.setForeground(UIManager.getColor("Tree.foreground"));
          add(new JLabel("World"));
       public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected, boolean expanded,
                                                     boolean leaf, int row, boolean hasFocus)
          custom.setText("("+value.toString()+")");
          return this;
    }

    My only advice would be to remember that rendered components are not actually added to the tree, so they are not a child of the tree... they actually cannot be clicked on. The rendered components are quickly used just to paint and specific image and then discarded (which is why you don't typically want to create new ones each time). When you click on the tree, there is no "rendered component" there, just an image that was painted.
    Hope this helps
    Josh Castagno
    http://www.jdc-software.com

  • "Object reference not set to an instance of an object" when opening designer

    I have a Windows Forms project which was originally developed in Visual Studio 2010. I migrated the project to VS2013, and now every time I open the project's main form, the designer complains of a null reference. If I hit "Ignore and Continue",
    the code compiles just fine. The error in question appears in the "Windows Form Designer generated code" region. Even more curious, the line in question is not the first reference to the object. It's as if the first few times it needs to interact
    with the object, it's fine, then at a certain point it becomes null.
    Here is the call stack for the error:
    at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component,
    Object value)at
    Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkPropertyDescriptor.SetValue(Object
    component, Object value)at
    System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializePropertyAssignStatement(IDesignerSerializationManager
    manager, CodeAssignStatement statement, CodePropertyReferenceExpression
    propertyReferenceEx, Boolean reportError)at
    System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeAssignStatement(IDesignerSerializationManager
    manager, CodeAssignStatement statement)at
    System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager
    manager, CodeStatement statement) 
    And here is the code in question:
    this.optionsControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); 
    this.optionsControl.IsAsciiMode = false;           
    this.optionsControl.Location = new System.Drawing.Point(3, 3);
    this.optionsControl.LogControl = null;           
    this.optionsControl.Name = "optionsControl";           
    this.optionsControl.PlugInManager = null;           
    this.optionsControl.PortFacade = null;           
    this.optionsControl.Size = new System.Drawing.Size(613, 259);
    this.optionsControl.TabIndex = 0;
    The problem is reported at the third line, "this.optionsControl.Location = new System.Drawing.Point(3, 3);".

    Hi Eric,
    I have made a research about your issue, and I found it might be caused by the usercontrol in the project. Was “this.optionsControl” a UserControl? It seems that this issue was difficult to handle.
    If possible, I would recommend you recreate this control in a new project.
    In addition, I think you could turn to the links below, they may be useful to you:
    # How to get more information about exceptions thrown by the designer when switching from code to design view?
    http://community.sharpdevelop.net/forums/p/16124/43105.aspx
    # How to avoid WSODs in the Visual Studio 2005 Designer
    http://www.codeproject.com/Articles/13584/How-to-avoid-WSODs-in-the-Visual-Studio-Desig
    # design time error: object reference not set an instance of an object but runs fine
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/b3676bef-e457-4aac-b438-d3ed8a667e3f/design-time-error-object-reference-not-set-an-instance-of-an-object-but-runs-fine?forum=winforms
    Best Regards,
    Edward
    This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; therefore,
    Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you
    completely understand the risk before retrieving any software from the Internet.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

  • Business object type for parked invoices

    Hi,
    We are using documentum to store documents that have been attached to business object types in SAP. The business object types are configured in transaction OAC3 to point to a pre-configured content repository.
    Having this configuration allows the object type to use the "services for objects" option, enabling it to store attachments.
    The business object types for invoices have been configured and we are able to store attachments. However this does not seem to work for "Parked invoices". The configuration in the "services for objects" component is not there and the feature to store the attachment is disabled.
    As the configuration needs to be done for all object types that need to be able to store attachments, maybe someone here can indicate what the object type is for parked invoices. Alternatively, maybe there is a way to look up the various business object types.
    Any help you can provide is appreciated.
    Thanks.
    Kind Regards,
    Giwan

    Hi ,
    Thank You for your reply.
    I created inquiry . it takes BUS2031.But BUS2031 is used for quotation.But that inquiry is open in VA12(Change Inquiry) Transaction,not open in VA22(Change Quotation).
    Is there any setting for BOR object types to Document Types.
    Please give me a reply as early as possible.It's very urgent.
    Thanks,
    Saritha

  • Error testing Web Dynpro Callable Object (GP Interface)

    With reference to thread:
    Interactive form as  Callable object error on testing the object.
    FYI, I'm running NW04s, EP 7.0 SPS 13, JDK 1.4.2_14, Unix OS
    Hi All,
    I have created a Web Dynpro App with a Adobe Form as the frontend. I have included the caf/eu/gp/api as a DC and implemented the IGPWebDynproCO interface. Next I created a Web Dynpro Callable object in GP and ran a test and received the following error:
    Result: Technical Exception
    Details: Could not create web dynpro callable object component
    Output Parameters
    Callable object implementation did not return  output parameters
    Can anyone help me resolve this? Do I have to make a manual entry in the HOST file? If so, what is that entry? Are there alternatives?
    Thanks
    Kunal.

    Hi,
    For creating WD callable object you need to add following three DC in your WD DC project.
    In the Web Dynpro Explorer of the Web Dynpro Perspective, expand the node DC MetaData -> DC Definition, and select Used DCs.
    a.      To create a DC dependency, open the context menu and choose Add Used DC.
      b.      Select Local Development  -> SAP-EU  -> caf/eu/gp/api/wd  -> DC MetaData  -> Public Parts  -> GPWebDynproCO. For Dependency Type, select Build Time, Design Time, and Run Time. Choose weak from the dropdown list.
      c.      Repeat the previous step to define a dependency to DCs SAP-EU-> caf/eu/gp/api (public part external) and SAP-JEE -> com.sap.security.api.sda (public part default).
    You need to do one more thing like bellow.
    Select your Web Dynpro project and open its context menu. Choose Properties.
    1. Choose Web Dynpro References -> Library References.
    2.  Add a reference for library caf/eu/gp/api.
    I think this will help you.
    Thanks
    Chandan

  • Getting error while creating callable object

    Hi,
    I've created and deployed a DC using webdynpro.
    Now I want to create a callable object from portal
    I'm choosing the following options Guided Procedurers-->DesignTime>Create callable object-->userinterface>webdynprocomponent(GP interface)
    On entering the required data on the displayed page, when I'm clicking 'next' option it is giving <b>"500 internal server error"</b>.
    Can somebody help how to resolve this.
    Thanks
    Piyush

    your callable object component is missing. try to take preview of the iview and check.

Maybe you are looking for