Mousemotion

Is there any way to sence the position of the mouse's cursor in an applet without Swing?

Well I will proceed with what is based on above.
I'll show you now how to create a Polygon (based on your movements)
We use the Polygon class for this purpose:
All code is the same as above (unless changed and noted).
private Polygon shape; // This one must be declared global too
public void init() {
  // As above
  shape = new Polygon();
public void mouseMoved(MouseEvent e) {   
  int x = e.getX();  // Both local variables for this method   
  int y = e.getY();   
  Point p = new Point(x,y);  // Initialize a local variable point   
  points.addElement(p); // Add the point to the vector, note that p, in fact becomes 'global' as it is referenced from the vector now 
  // Here we add the points to the Polygon
  shape.addPoint(x,y);
  repaint();  // Once a point is added re-draw the polygon
// Override the paint method and draw your polygon
// It is however not FAST to do it this way
// But it does show you the idea on how to use the Polygon class
public void paint(Graphics g) {
  g.setColor(Color.BLACK);
  if(shape != null)
    g.drawPolygon(shape);
}To enhance the code you can buffer drawing in memory. (offscreen buffer). There are several postings about this problem, so I suggest to look around if you need it.
The Vector class in this case is not necessary anymore, as you draw the Polygon right away. However if you do not wish to draw the Polygon all the time (which is far better for performance) you can use this one and later create a new polygon and add the Points (that are stored in the Vector class) to the polygon and then draw it.
Martijn

Similar Messages

  • MouseMotion on a class that's not an extended Component

    Hi, i'm trying to make a class that has the addMouseMotion(MouseEvent e) on it, but i can't make it work, this class has nothing to do with the class componet so i can't use it.
    I saw some people's code using a Vector of MouseMotionListener and implementing MouseMotion interface but i don't seem to make it work. Can someone help me out?
    Here's the code:
    class Whatever implements MouseMotionListener
    Vector motionListeners = new Vector();
    public void addMouseMotionListener(MouseMotionListener l)
    motionListeners.add(l);
    public boolean removeMouseMotionListener(MouseMotionListener l)
    return motionListeners.remove(l);
    public void mouseMove(MouseEvent e)
    Enumeration e = motionListeners.elements();
    ((MouseMotionListener)e.nextElement()).mouseMove(e);
    public void mouseDrag(MouseEvent e)
    Enumeration e = motionListeners.elements();
    ((MouseMotionListener)e.nextElement()).mouseDrag(e);

    From Enumeration javadoc:
    NOTE: The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.
    From Iterator javadoc:
    An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
    * Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
    * Method names have been improved.
    The best thing you could do is to debug you app, either with System outputs or by using a debugger. E.g. there's a gui debugger integrated in JBuilder and propably in Forte, too.
    Then you can step through your program.
    Otherwise I needed more code relevant to this problem (where do you register an object of this class to a MouseMotion source? Where do you register other MouseMotionListeners to this object?).
    Greets
    Puce

  • How to clear the the rectangle........

    Hello,
    I'm doing a project in swings and i have drawn a rubberband rectangle in buffered image once the user clicks and drags mouse the dotted lines appear showing the boundary of rectangle and when the button is released the lines should become solid .
    But in my case after releasing the button the dotted lines will remain within the rectangle but i need only the outer lines of rectangle to be there.
    How to make those lines invisible which are in side the rectangle.
    Can anybody suggest some method to do it ?
    Thanks in advance,
    The code is:
    // Rubber1.java    basic rubber band for shape
    //                 Draw rectangle. left mouse down=first point     
    //                 Drag to second point. left mouse up=final point
    //                 right mouse changes color of first figure area
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class Rubber1 extends JPanel
      int ax,ay,bx,by;     
      int winWidth = 500;
      int winHeight = 500;
      boolean tracking = false; // left button down, sense motion
      int startX = 0;
      int startY = 0;
      int currentX = 0;
      int currentY = 0;
      int num_fig = 0; // number of figures to draw
      int select = 0;  // the currently selected figure index
      Fig figure[] = new Fig[50]; // num_fig is number of figures to display
      BufferedImage BuffImage ;
      Graphics2D gb;
      Rubber1()
        //setTitle("Spiral");
        setSize(winWidth,winHeight);
        setBackground(Color.white);
        setForeground(Color.black);
        BuffImage = new BufferedImage(10,10,BufferedImage.TYPE_INT_ARGB);
        gb = BuffImage.createGraphics();
        gb.setColor(Color.BLACK);
        /*addWindowListener(new WindowAdapter()
          public void windowClosing(WindowEvent e)
            System.exit(0);
        setVisible(true);
        this.addMouseListener (new mousePressHandler());
        this.addMouseListener (new mouseReleaseHandler());
        this.addMouseMotionListener (new mouseMotionHandler());
      class Fig // just partial structure, may add more
        int kind;           // kind of fig
        int x0, y0, x1, y1; // rectangle boundary
        double r, g, b;     // color values
        double width;
        Fig(){ kind=0; x0=0; y0=0; x1=0; y1=0;
                      r=0.0; g=0.0; b=5.0; width=0.0;}
         void mouseMotion(int x, int y)
            if(tracking)
             currentX = x;
             currentY = y;
             requestFocus();
             repaint();
          void startMotion(int x, int y)
            tracking = true;
             startX = x;
             startY = y;
             currentX = x;
             currentY = y; // zero size, may choose to ignore later
             requestFocus();
             repaint();
         void stopMotion(int x, int y)
           tracking = false; // no more rubber_rect
           // save final figure data for 'display' to draw
           currentX = x;
           currentY = y;
           figure[num_fig] = new Fig();
           figure[num_fig].kind = 1; /* just rectangles here */
           figure[num_fig].x0 = startX;
           figure[num_fig].y0 = startY;
           figure[num_fig].x1 = currentX;
           figure[num_fig].y1 = currentY;
           figure[num_fig].r = 1.0;
           figure[num_fig].g = 0.0;
           figure[num_fig].b = 0.0;
           figure[num_fig].width = 2.0;
           num_fig++;
           requestFocus();
           repaint();
      class mousePressHandler extends MouseAdapter
        public void mousePressed (MouseEvent e)
          int b;
          b = e.getButton();
          ax = e.getX();
          ay = e.getY();
           System.out.println("press x="+ax+"   y="+ay+" "); // debug print
          if(b==1) startMotion(ax, ay);  // right mouse
          if(b==3) pick(ax, ay);         // left mouse
        @Override
        public void mouseClicked(MouseEvent e)
             int n =0,o;
             if(MouseEvent.BUTTON3==e.getButton())
             n = e.getX();
             o = e.getY();
             menu( n , o);
        public void menu(int n ,int o)
             JFrame.setDefaultLookAndFeelDecorated(true);       
             JFrame frame = new JFrame("Parameters");
           // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel();
            frame.add(panel,BorderLayout.SOUTH);
            JButton b1 = new JButton("PLOT");
            panel.add(b1);
          /*  b1.addActionListener(new ActionListener()
                 public void actionPerformed(ActionEvent arg2)
                       Spiral spiral = new Spiral();
            b1.setMnemonic(KeyEvent.VK_P);
            JButton b2 = new JButton("CANCEL");
            panel.add(b2);
           b2.setMnemonic(KeyEvent.VK_C);
            b2.addActionListener(new ActionListener()
                 public void actionPerformed(ActionEvent arg1)
                      System.exit(0);
            JMenuBar menubar = new JMenuBar();
            JMenu degmenu = new JMenu("Angle(D)");
            degmenu.add(new JSeparator());
            JMenu colmenu = new JMenu("Color");
           // colmenu.add(new JSeparator());
            JMenu spamenu = new JMenu("Spacing");
            //spamenu.add(new JSeparator());
            JMenuItem degItem1 = new JMenuItem("5");
            JMenuItem degItem2 = new JMenuItem("10");
            JMenuItem degItem3 = new JMenuItem("15"); 
            JMenuItem colItem1 = new JMenuItem("Color");
            colItem1.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent arg0)
                        // TODO Auto-generated method stub
                        ColorChooser chooseColor = new ColorChooser();
                        JFrame frame = new JFrame();
                        frame.setSize(450,330);
                        frame.add(chooseColor);
                        frame.setVisible(true);
                       //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            degmenu.add(degItem1);
            degmenu.add(degItem2);
            degmenu.add(degItem3);
            colmenu.add(colItem1);
            menubar.add(degmenu);
            menubar.add(colmenu);
            menubar.add(spamenu);
            frame.setJMenuBar(menubar);
            frame.setSize(180,120);
            frame.setVisible(true);  
            frame.setLocation( n+5 , o+5 );
      class mouseMotionHandler extends MouseMotionAdapter
        public void mouseDragged (MouseEvent e)
          int x, y;
          int b;
          b = e.getButton();
          x = e.getX();
          y = e.getY();
          mouseMotion(x, y);
         // rubberRect rub = new rubberRect();
      class mouseReleaseHandler extends MouseAdapter
        public void mouseReleased (MouseEvent e)
          int b; //int x, y;
          b  = e.getButton();
          bx = e.getX();
          by = e.getY();
          if(b==1) stopMotion(bx, by);
          System.out.println("press x=" +bx+"    y="+by+" ");
       public void rubberRect(Graphics2D gb, int x0, int y0, int x1 , int y1)
          // can apply to all figures
          // draw a rubber rectangle, mouse down, tracks mouse
           int x,y,x2,y2,x3,y3; // local coordinates
           x2=x0;
           x3=x1;
           if(x1<x0) {x2=x1; x3=x0;};
           y2=y0;
           y3=y1;
           if(y1<y0){y2=y1; y3=y0;};
             //gb.setColor(Color.black);
           for(x=x2; x<x3-3; x=x+8) // Java does not seem to have a
             {                        // dashed or stippled rectangle or line
               gb.drawLine(x, y0, x+4, y0);
               gb.drawLine(x, y1, x+4, y1);
           for(y=y2; y<y3-3; y=y+8)
               gb.drawLine(x0, y, x0, y+4);
               gb.drawLine(x1, y, x1, y+4);
      void fillRect(Graphics2D gb, Fig rect)
        int x, y;
        gb.setColor(new Color((float)rect.r, (float)rect.g, (float)rect.b));
        // g.setLineWidth(rect.width); ???
        x=rect.x0;
        if(rect.x1<rect.x0) x=rect.x1;;
        y=rect.y0;
        if(rect.y1<rect.y0) y=rect.y1;
        gb.drawRect(x, y, Math.abs(rect.x1-rect.x0),Math.abs(rect.y1-rect.y0));
        if(rect.width>1.0)
        gb.drawRect(x-1, y-1, Math.abs(rect.x1-rect.x0)+2,Math.abs(rect.y1-rect.y0)+2);
        //gb.clearRect(startX-10,startY-10,currentX-10,currentY-10);
      void pick(int x, int y)
        int i;
       // float t; search figures in list, select
        for(i=0; i<num_fig; i++)
          if(figure.x0 < figure[i].x1)
    if(x<figure[i].x0 || x>figure[i].x1) continue;
    if(figure[i].x1 < figure[i].x0)
    if(x<figure[i].x1 || x>figure[i].x0) continue;
    if(figure[i].y0 < figure[i].y1)
    if(y<figure[i].y0 || y>figure[i].y1) continue;
    if(figure[i].y1 < figure[i].y0)
    if(y<figure[i].y1 || y>figure[i].y0) continue;
    // select here by just changing color
    figure[select].r = 1.0;
    // figure[select].g = 0.0;
    select = i;
    figure[select].r = 0.0;
    // figure[select].g = 1.0;
    break;
    requestFocus();
    // repaint();
    protected void paintComponent(Graphics g)
    Graphics2D gb=(Graphics2D)g;
    //gb.setXORMode(getBackground());
    // gb.setXORMode(Color. gray); //border color
    if(tracking==true)rubberRect(gb,startX,startY,currentX,currentY);
    gb.drawImage(BuffImage,ax,ay,Color.white,this);
    for(int i=0;i<num_fig;i++)
    fillRect(gb, figure[i]);
    // gb.clearRect(startX-10,startY-10,currentX-10,currentY-10);
    public static void main(String args[])
         JFrame f = new JFrame();
         f.setSize(500,500);
         Rubber1 r = new Rubber1();
         f.add(r);
         f.setVisible(true);
    //new Rubber1();
    Edited by: sumukha on Nov 15, 2007 1:19 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Two things,
    1) Java does have dashed lines. Look into BasicStroke. You'll have to cast your Graphics object into a Graphics2D to use it, but it's quite simple to use.
    See http://java.sun.com/j2se/1.4.2/docs/guide/2d/spec/j2d-awt.html section 2.3.2.3.
    2) Rubber banding is much easier to do using XOR mode. The first drawing will use the difference between the color you're set at and the background. The second drawing over the same place with the same color will reverse the process. So to use it, you draw your rubber band, then to remove it, you draw over the old one without changing anything. You'll have to keep track of the last known position of the shape, but it's not too difficult once you get the hang of it. Use setPaintMode() to return to normal drawing. I couldn't find a good example on the net, so here's a simple example for a rectangle only:
       public void drawShape() {
          if (mCurrentRect != null) {
             Graphics2D g = (Graphics2D)getGraphics();
             if (mIsPermanent) {
                g.setPaintMode();
             } else {
                g.setXORMode(getBackground());
             g.draw(mCurrentRect);
             g.dispose();
       public void mousePressed(MouseEvent evt) {
          mCurrentRect = new Rectangle(evt.getX(), evt.getY(), 0, 0);
          mIsPermanent = false;
          drawShape();
       public void mouseDragged(MouseEvent evt) {
          if (mCurrentRect != null) {
             drawShape();      // Remove shape
             mCurrentRect.setRect(mCurrentRect.getX(), mCurrentRect.getY(), evt.getX(), evt.getY());
             drawShape();      // Redraw it
       public void mouseReleased(MouseEvent evt) {
          if (currentShape != null) {
             drawShape();      // Remove shape
             mCurrentRect.setRect(mCurrentRect.getX(), mCurrentRect.getY(), evt.getX(), evt.getY());
             mIsPermanent = true;
             drawShape();      // Redraw it
             mRectangleList.add(mCurrentRect); // iterate through in paintComponent to draw these
             mCurrentRect = null;
       }

  • RePaint() bug or doing something wrong?

    Im writing an application which consist of a JFrame and two JPanels.
    They are laid out with a BoxLayout.
    The upper JPanel basiclly draws an image out.
    The lower JPanel is listening for mousemotionevents from the upper JPanel. Whenever a mousemotion events occur I write the x,y - coords of the mouse out in the lower JPanel.
    The lower JPanel's code look somthing like this:
    public class LowerPanel extends JPanel implements MouseMotionListener{
    UpperPanel.addMouseMotionListener(this);
    public void mouseMoved(MouseEvent e){
    updating x,y coords..
    repaint();
    public void paint(Graphics e){
         e.clearRect(10,10,100,50);
         e.drawString("Coordinates of mouse.... x,y=...");
    Now to the problem.. when the program starts everything looks ok with two panels, the upper panel showing the image and the lower panel drawing the "default" coords of 0,0. As soon as I start moving the mouse inside the upper panel the image of the upper panel is drawn inside the lower Panel as well?! Except from that everything works as it should. The coords are updating when I move the mouse but.. with the upper panels image as background to it heh.. does anyone know what is causing this and how to fix it? Please :]

    to make the problem more clear:
    It seems like the lower Panel captures the upper Panel's output somehow and draws it out before drawing it's own content. (?!)
    I really need help with this one.. no idea what im doing wrong. :[                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Do I use DnD or MouseMotionListener ?

    I am wondering about the pros and cons of using dnd api vs. MouseListener/MouseMotionListener.
    I am experimenting with drag-and-drop using a simple app that allows components to be rearranged by dragging.
    Here is a description of desired test program behavior:
    For instance, if 5 rectangular panel components [A,B,C,D,E] are in a vertical row, and B is dragged onto D, then it is meant that B should be moved to before D, so the components will jump to new order [A,C,B,D,E]. (This is a simple test app for my learning, so I am ignoring that nothing can be moved to after E.)
    There is a visual indicator during the drag operation. In the above example where B, the dragsource, is dragged to D:
    - When drag begins, dragsource is on B, so indicator is a little notch arrow between A and B.
    - When drag moves onto C, notch arrow jumps to between B and C.
    - When drag moves onto D, notch arrow jumps to between C and D.
    - When drag released on D, components jump to rearrage themselves as user would expect from indicator arrow position.
    If drag goes outside the 5 components, the indicator arrow will stay where it was (i.e. it only updates at enter not exit)
    If mouse released outside the 5 components (or outside app window), the drag/move operation is aborted: the indicator goes away and no components move.
    The dragged-into component listener calls to parent panel to update the indicator arrow.
    The dropped-onto component listener calls to parent panel to reorder children.
    This description is pretty sound and simple in theory, but I am new to MouseMotionListener and java.awt.dnd. Which is better for this purpose?
    DND:
    - Can use listener to tell me about the enter, drop, and dragEnded events.
    - Since my app is not truly performing datatransfer, I would need to fool it with adding new action or dataflavor type (so not to mix up with other types of dragsources and targets).
    - I don't know how to discover the dragged component from a DropTargetDragEvent
    MouseMotion:
    - Would probably simplify everything and shorten my code.
    - Can use listener to tell me about the drag, enter, and release events.
    - Don't know how I would detect/handle the cases where mouse moved/released outside the application or outside the listening components.
    /Mel
    I will post the so-far-source if anyone is actually interested to see it.

    Hi,
    I know it kinda very late as its been a while since you posted your question, but i realized that is exavtly what i am trying to achieve in my project. Move labels within a panel among themselves. I was wondering if you might still have to code and if so, can you please send it to me?? my email id is [email protected]
    or if ou dont, and you do read this email, I would really appreciate it if you can let me know how?
    thanks very mucg,
    Sri.

  • Text displayed when mouse at coordinate

    Hi,
    I think this is a hard one. I've been looking around the net on how to do this, can't find any info.
    Firstly is this hard to implement?
    The problem:
    I have a JPanel. What I want to happen is some predetermined text to appear over the mouse or in a JTextField on another panel, when the mouse moves over or within 5 pixels of different coordinates. Text above the mouse would be my prefferable implementation.
    What do I need to look at to findout how this can be implemented?
    Thanks again.
    Ben.

    Hi,
    I took your advice and came up with the following. I have a class that initialises the MouseMotion class (code below). In the initialising class I have also used ToolTipManager.sharedInstance().setEnabled(true); to enable the tooltips for the whole application. I also added the listener to a panel using panel1.addMouseMotionListener(mouseListener);. (adding tooltips to buttons etc works fine)
    The code below prints a line to the screen when the mouse is moved over a coordinate on the panel. How do I change this to a tooltip?
    Thanks for any help.
    Ben.
    import java.awt.*;
    import java.awt.event.*;
    public class MouseMotion implements MouseMotionListener
    // The X-coordinate and Y-coordinate ofthe last Mouse Position.
    int xpos;
    int ypos;
    public void mouseMoved(MouseEvent me)
    xpos = me.getX();
    ypos = me.getY();
    if(xpos = 10 && y pos == 10)
    System.out.println("Area 1");
    if(xpos = 20 && y pos == 20)
    System.out.println("Area 2");
    if(xpos = 30 && y pos == 30)
    System.out.println("Area 3");
    public void mouseDragged(MouseEvent me)
    }

  • Mouse-Drag / Dialog bug

    hello.
    everytime I aknlowledge a file browser (in WindowsXP) of class FileDialog by double-clicking an entry, a MouseMotion-Event: "mouseDragged" is fired on an underlying Canvas behind the file dialog, resulting in irrational scrolling of my application.
    It seems the last click of the double-click inside the dialog is irregular recognized by the canvas, even it is hidden by the dialog at this moment. also the file dialog is a full native windows gui object so this seems just crazy...
    anyone any idea / workaround? i would be very pleased.
    thanks & greets
    Paul

    bah
    ok this would work for sure
    but the canvas has nothing todo with the dialog-launching loader. this would be very dirty non-oop... i have to tell the canvas crossing many object references, which arent public, then need senseless getters...
    this would work better within a small app for sure..
    nevertheless thanks; i just wait some time, otherwise you get the dukes
    greets

  • Mouse Drag Box & get coordinates

    Hi, is there a API to do this. If you click the mouse button and drag it I want a box to appear on the screen. When they release I want to get the coordinates of the box. I have seen it commonly done in programs like Photoshop and even in java applets on the web. I want to know if theres a API to do this before writing it myself. Thanks.

    should be possible using moue and mousemotion listeners.
    You check if currently a dragging happens and if so drawrect.
    It could get slow and make jumps if you have lots of graphic behind since you have to redraw that every time.

  • Hovering text needed

    does any1 know how to get hovering text when the mouse cursor passes over an image, say a photo thumbnail?
    TIA

    sure, you just need to have a mouseMotion listener which checks to see if it's x/y cord are over the region you want. If they are you paint your text, if not then don't paint the text

  • Transparent JLabel

    Hi,
    I'm actually doing developing a JFrame that implements mousemotion listener. What I do first is that in the paint function I draw
    some circles using g.drawOval. Then when the mouse is over any one of the circle I will add a JLabel over the particular circle. The problem here is that the JLabel overwrites the circle below it and disolves the cirles partially. So how can I make it such a way that the JLabel will be tranparent over the circles.

    Hi,
    Run this demo pasted below and tell it creates a transparent label.
    Regards,
    Pratap
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.String.*;
    import javax.swing.*;
    public class test1 extends JFrame implements MouseMotionListener
         Container container;
         JLabel label1;
         boolean bDomain = false;
         public test1()
              super("GridLayout Demo");
              container = getContentPane();
              container.setLayout(null);
              container = this.getContentPane();
              container.addMouseMotionListener(this);
              bDomain = true;
              setSize(600, 600);
              show();
         public void paint(Graphics g)
              if (bDomain == true) {
                   g.drawOval(50, 50, 40, 40);
         public void mouseMoved(MouseEvent e)
              int x;
              int y;
              x = e.getX();
              y = e.getY();
              if (((x >= 50) && (e.getX() <= (50 + 40))) &&
                        ((e.getY() >= 50) && (e.getY() <= (50 + 40)))) {
                   label1 = new TransparentLabel("Circle : 1 "); // here is the problem occur when add the label
                   label1.setOpaque(false);
                   container.add(label1);
                   label1.setBounds(50, 50, 50, 50);
                   super.repaint();
         public void mouseDragged(MouseEvent e) {}
         public static void main(String[] args)
              test1 app = new test1();
              app.addWindowListener(new WindowAdapter() {
                        public void windowCLosing(WindowEvent e)
                             System.exit(0);
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class TransparentLabel extends JLabel {
         BufferedImage im;
         public TransparentLabel(String text) {
              super(text);
              setIgnoreRepaint(true);
         protected void paintComponent(Graphics g) {     g.drawString(getText(),10,10);}
    }

  • Networks

    Does anyone konw how you can send events across a network and handle them at the receiving computer e.g. if I send a mousemotion event across a network could I handle it at the other end

    MouseEvent implements Serializable so maybe take a look at RMI.

  • Event listening

    Hi
    I am preparing a childs mathematics tutorial in which an exercise is to arrange objects in order. I have mouse and mousemotion listeners inplace in order to move the objects around the screen. However when the objects are in the required location on the screen, i now wish to calculate using listeners if the objects are in the correct place and as a result increment the results counter. Could an one help to solve my problem in measuring this.
    I am using JLabels for the pictures and i had already attempted to get the position of both labels on the screen and say something like
    JLabel[0].getPosition
    JLabel[1].getPosition
    if( position == position) also tried (equals() function)
    do.......
    ( where position is a point)
    this didn't work!
    any ideas?
    thank you

    use get Location() not getPosition().
    Point p1 = JLabel[0].getLocation();
    Point p2 = JLabel[1].getLocation();
    if (p1.equals(p2))
    do.......

  • Mouse Motion Problem

    I have a JFrame which I have added a MouseMotion Listener to it, it contains many JPanels with border layout manager. I want to detect a MouseMotion in the whole Frame. But I found that only the menu bar area could fire a MouseMotionEvent when the cursor moves there. There are no mouse motion event be fired when the mouse moves on other area on the Frame. What should I do to make it works? Or should I do anything to those insided JPanels ?

    Add your MouseMotionListener to the frame's glass pane. Be sure to set the glass pane visible in order to retrieve the mouse moved events. See attached sample working code.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class GlassMotion
      public static void main(String args[])
        new GlassMotionFrame();
    class GlassMotionFrame extends JFrame implements ActionListener
      JMenuBar mb = new JMenuBar();
      JMenu file = new JMenu("File");
      JMenu edit = new JMenu("Edit");
      JMenu view = new JMenu("View");
      JMenu help = new JMenu("Help");
      JSeparator separator = new JSeparator();
      JMenuItem fileOpen = new JMenuItem("Open...");
      JMenuItem fileSaveAs = new JMenuItem("Save As...");
      JMenuItem editCut = new JMenuItem("Cut");
      JMenuItem editCopy = new JMenuItem("Copy");
      JMenuItem editPaste = new JMenuItem("Paste");
      JMenuItem helpAbout = new JMenuItem("About...");
      JPanel north = new JPanel();
      JPanel south = new JPanel();
      JPanel center = new JPanel();
      JTextField jtf = new JTextField(20);
      JTextArea jta = new JTextArea(20,30);
      JScrollPane jsp = new JScrollPane(jta);
      JButton ok = new JButton("OK");
      GlassMotionFrame()
        super();
        /* Components should be added to the container's content pane */
        Container cp = getContentPane();
        Component glassPane = getGlassPane();
        glassPane.addMouseMotionListener(new MouseMotionAdapter() {
          public void mouseMoved(MouseEvent evt) {
            System.out.println("Mouse motion event!");
        glassPane.setVisible(true);
        north.add(new JLabel("Last Name:"));
        north.add(jtf);
        center.add(jsp);
        south.add(ok);
        cp.add(BorderLayout.NORTH,north);
        cp.add(BorderLayout.CENTER,center);
        cp.add(BorderLayout.SOUTH,south);
        /* Add menu items to menus */
        file.add(fileOpen);
        file.add(separator);
        file.add(fileSaveAs);
        edit.add(editCut);
        edit.add(editCopy);
        edit.add(editPaste);
        help.add(helpAbout);
        /* Add menus to menubar */
        mb.add(file);
        mb.add(edit);
        mb.add(view);
        mb.add(help);
        /* Set menubar */
        setJMenuBar(mb);
        /* Add the action listeners */
        fileOpen.addActionListener(this);
        fileSaveAs.addActionListener(this);
        editCut.addActionListener(this);
        editCopy.addActionListener(this);
        editPaste.addActionListener(this);
        helpAbout.addActionListener(this);
        /* Add the window listener */
        addWindowListener(new WindowAdapter()
          public void windowClosing(WindowEvent evt)
            dispose();
            System.exit(0);
        /* Size the frame */
        pack();
        /* Center the frame */
        Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle frameDim = getBounds();
        setLocation((screenDim.width - frameDim.width) / 2,(screenDim.height - frameDim.height) / 2);
        /* Show the frame */
        setVisible(true);
      public void actionPerformed(ActionEvent evt)
        Object obj = evt.getSource();
        if (obj == fileOpen);
        else if (obj == fileSaveAs);
        else if (obj == editCut);
        else if (obj == editCopy);
        else if (obj == editPaste);
        else if (obj == helpAbout);
    }

  • MouseMotionListener

    Hey there,
    I know that's a mad question, but i'm sure u guys can help me out.
    I have implemented a MOuseMotion Listener.
    public void mouseDragged(MouseEvent e) {
          textArea11.append("mouseDragged event"+newline);
          }from where do i get the info of the objects instance on which the mouse was dragged e.g. myTextField?
    e.getComponent().getClass().getName() is not what i am looking for...
    thanks,
    stonee

    public void mouseDragged(MouseMotionEvent e){
    if( e.getSource() == textArea11 ){
    //..code goes here
    }

  • Mouse motion events

    For some reason my custom JComponent or cutom Jpanel do not detect any mouseMotion events. Does anyone know why that is?
    I have a class like the following
    public class GeometryPanel  extends JComponent implements MouseInputListenerin my main class (the frame class) I have the following
             JFrame frame = new JFrame();
         JPanel p = new MyPanel();
         JComponent geometryPanel;
         JComponent buttonPanel = new ButtonPanel(this);
         public MainWindow()
              geometryPanel = new GeometryPanel(this,600, 600);
              setupGUI();
              displayFrame();
         public void setupGUI()
               p.setBackground( Color.white );
              p.setPreferredSize(new Dimension(width, height));
              geometryPanel.setPreferredSize(new Dimension(600, 600));
              buttonPanel.setPreferredSize(new Dimension(620, 80));
               p.add( geometryPanel );
               p.add( buttonPanel );
         public void displayFrame()
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(p);
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.show();
         }For some reason all of the mouse pressed events are caught, but not the motion events. They are not fired.

    Ah I got it, thank you. Forgot to add the mouse motion listener next to the mouse listner

Maybe you are looking for